leetcode59. spiral matrix ii 细节 总结

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

1
2
3
4
5
6
7
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

​ 16 ms 8.9 MB

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
vector<vector<int>> generateMatrix(int n) {
int num = 1;
int top = 0, right = n - 1, bottom = n - 1, left = 0;

vector<vector<int>> ret(n,vector<int>(n));
while (num<=n*n)
{
//top
for (int col = left; col <= right; col++)
ret[top][col] = num++;
if (++top > bottom) break;

//right
for (int row = top; row <= bottom; row++)
ret[row][right] = num++;
if (--right < left) break;

//bottom
for (int col = right; col >= left; col--)
ret[bottom][col] = num++;
if (--bottom < top) break;

//left
for (int row = bottom; row >= top; row--)
ret[row][left] = num++;
if (++left > right) break;//2.
}
return ret;
}

细节

  1. 二维数组初始化: vector<vector> ret( n, vector(n) );
  2. 越界大小判断,错了两次了

总结

螺旋矩阵一样,只不过是逆向思维,套路还是上右下左遍历,更新行列号,判断越界break。