题目: 螺旋矩阵 II
来自智得网
分析
模拟法
首先,我们定义 left
、right
、top
和 bottom
四个变量,分别表示当前待填充区域的左、右、上和下四个边界。我们从左上角开始,按照顺时针方向一圈一圈地填充矩阵。每次填充完一圈,我们更新边界,并检查是否需要继续填充。直到边界重合或者越界,算法停止。
以下是实现的详细步骤:
- 初始化一个大小为
n x n
的矩阵,并定义left
、right
、top
和bottom
四个变量,分别为 0、n-1、0 和 n-1。 - 定义一个变量
num
,表示当前待填充的数字,初始值为 1。 - 进入循环,循环条件为
left <= right && top <= bottom
。 - 从左到右填充一行,行号为
top
,列号从left
到right
。填充完成后,将top
加 1。 - 从上到下填充一列,列号为
right
,行号从top
到bottom
。填充完成后,将right
减 1。 - 如果此时
top <= bottom
,从右到左填充一行,行号为bottom
,列号从right
到left
。填充完成后,将bottom
减 1。 - 如果此时
left <= right
,从下到上填充一列,列号为left
,行号从bottom
到top
。填充完成后,将left
加 1。 - 重复步骤 4-7,直到边界重合或者越界。
- 返回填充完成的矩阵。
题解
模拟法
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
# 初始化矩阵
matrix = [[0] * n for _ in range(n)]
# 初始化边界
top, bottom, left, right = 0, n-1, 0, n-1
num = 1
# 按顺时针顺序填充数字
while num <= n * n:
# 从左到右
for i in range(left, right+1):
matrix[top][i] = num
num += 1
top += 1
# 从上到下
for i in range(top, bottom+1):
matrix[i][right] = num
num += 1
right -= 1
# 从右到左
for i in range(right, left-1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
# 从下到上
for i in range(bottom, top-1, -1):
matrix[i][left] = num
num += 1
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n, 0));
int num = 1, left = 0, right = n-1, top = 0, bottom = n-1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) {
matrix[top][i] = num;
num++;
}
for (int i = top+1; i <= bottom; i++) {
matrix[i][right] = num;
num++;
}
for (int i = right-1; i >= left; i--) {
if (top < bottom) {
matrix[bottom][i] = num;
num++;
}
}
for (int i = bottom-1; i > top; i--) {
if (left < right) {
matrix[i][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
}
};
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int num = 1, left = 0, right = n-1, top = 0, bottom = n-1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) {
matrix[top][i] = num;
num++;
}
for (int i = top+1; i <= bottom; i++) {
matrix[i][right] = num;
num++;
}
for (int i = right-1; i >= left; i--) {
if (top < bottom) {
matrix[bottom][i] = num;
num++;
}
}
for (int i = bottom-1; i > top; i--) {
if (left < right) {
matrix[i][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
}
}