Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

螺旋矩阵II

来源Leetcode第59题螺旋矩阵II

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]


层填充

思路和54题是一样的

对于每层,我们从左上方开始以顺时针的顺序填充所有元素,假设当前层左上角坐标是 (r1, c1),右下角坐标是 (r2, c2)。

首先,遍历上方的所有元素 (r1, c),按照 c = c1,…,c2 的顺序。然后遍历右侧的所有元素 (r, c2),按照r = r1+1,…,r2 的顺序。如果这一层有四条边(也就是 r1 < r2 并且 c1 < c2 ),我们以下图所示的方式遍历下方的元素和左侧的元素。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public int[][] generateMatrix(int n) {
int count = 1;
if(n <= 0 ) return null;
int [][] matrix = new int[n][n];
int r1 = 0, r2 = matrix.length - 1;
int c1 = 0, c2 = matrix[0].length - 1;
while (r1 <= r2 && c1 <= c2) {
for (int c = c1; c <= c2; c++) {
matrix[r1][c] = count;
count++;
}
for (int r = r1 + 1; r <= r2; r++) {
matrix[r][c2] = count;
count++;
}
if (r1 < r2 && c1 < c2) {
for (int c = c2 - 1; c > c1; c--) {
matrix[r2][c] = count;
count++;
}
for (int r = r2; r > r1; r--) {
matrix[r][c1] = count;
count++;
}
}
r1++;
r2--;
c1++;
c2--;
}
return matrix;
}

模拟

绘制螺旋轨迹路径,我们发现当路径超出界限或者进入之前访问过的单元格时,会顺时针旋转方向。
假设数组有 R 行 C 列,seen[r][c] 表示第 r 行第 c 列的单元格之前已经被访问过了。当前所在位置为 (r, c),前进方向是 di。我们希望访问所有 R x C 个单元格。
当我们遍历整个矩阵,下一步候选移动位置是 (cr, cc)。如果这个候选位置在矩阵范围内并且没有被访问过,那么它将会变成下一步移动的位置;否则,我们将前进方向顺时针旋转之后再计算下一步的移动位置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public int[][] generateMatrix(int n) {
int count = 1;
if(n <= 0 ) return null;
int [][] matrix = new int[n][n];

//4次转向的方向
int [] dir_i = {0,1,0,-1};
int [] dir_j = {1,0,-1,0};
//定义行数和列数
int row = n;
int cols = n;
int index = 0; // 方向索引
int pos_i = 0, pos_j = -1 ; //位置索引
int len;
while (count < n * n + 1){
//获得当前遍历行或列的长度
if(index == 0 || index == 2)
len = cols;
else len = row;

for(int i = 0 ; i < len ; i++){
//遍历行or列

//计算当前位置
pos_i = pos_i + dir_i[index];
pos_j = pos_j + dir_j[index];
matrix[pos_i][pos_j] = count;
count ++ ;
if(count == n * n + 1)
return matrix;
}

if(index == 0 || index == 2)
//更新边界值
row--;
else if (index == 1 || index == 3)
cols--;

index = (index + 1) % 4; // 换向
}

return matrix;
}