题目链接:59. 螺旋矩阵 II

题解:

螺旋矩阵问题,和上一个基本类似。

题目简述:

给定一个数字 n,按照从右、下、左、上的顺序生成一个螺旋矩阵!

题解:

54题-螺旋矩阵类似,同样使用两个方向数组,参考上一篇题解,同样是一个方向走到不能走就换方向。

此处的res数组存储每个位置要填的值!

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
vector<vector<bool>> vis(n, vector<bool>(n));
for(int i = 1, x = 0, y = 0, d = 0; i <= n * n; i++){
res[x][y] = i;
vis[x][y] = true;
int a = x + dx[d], b = y + dy[d];
if(a < 0 || a >= n || b < 0 || b >= n || vis[a][b]){
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
return res;
}
};