leetcode-----59. 螺旋矩阵 II
代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n));
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
for (int i = 0, d = 0, x = 0, y = 0; i < n * n; ++i) {
ans[x][y] = i + 1;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a == n || b < 0 || b == n || ans[a][b]) {
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
return ans;
}
};