59. Spiral Matrix II

题目

https://leetcode.com/problems/spiral-matrix-ii/description/

-w951

想法

其实就是考虑一些边界值,考虑的好,就写起来很简洁

还有四个方向的变化,怎么统一起来,一点小trick

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int i = 0, j = 0;
vector<int> h{1, 0, -1, 0};
vector<int> v{0, 1, 0, -1};
int d = 0;
res[i][j] = 1;
for (int k = 2; k <= n * n; k++) {
int ti = i + v[d];
int tj = j + h[d];
if (!(ti >= 0 && ti < n && tj >= 0 && tj < n && res[ti][tj] == 0)) {
d = (d + 1) % 4;
}
i = i + v[d];
j = j + h[d];
res[i][j] = k;
}
return res;
}
};