59. 螺旋矩阵 II

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0)); // 使用vector定义一个二维数组,全部元素初始化为零
int di[] = {0, 1, 0, -1};
int dj[] = {1, 0, -1, 0};
for(int i = 0, j = 0, d = 0, k = 1;k <= n * n;k++){
res[i][j] = k;
int iNext = i + di[d];
int jNext = j + dj[d];
if(iNext < 0 || iNext >= n || jNext < 0 || jNext >= n || res[iNext][jNext]){
d = (d + 1) % 4;
iNext = i + di[d];
jNext = j + dj[d];
}
i = iNext;
j = jNext;
}
return res;
}
};

54. 螺旋矩阵

C++