螺旋矩阵
c++
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>>res(n, vector<int>(n, 0));
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; //方向偏移数组
int x = 0, y = 0; //当前位置
for(int i = 1, d = 0; i <= n*n; i++)
{
res[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if(a <0 || a == n || b < 0 || b == n || res[a][b]){ //出界或者该位置已经被走过
d = (d + 1) % 4; //更改方向
a = x + dx[d], b = y + dy[d]; //下一个要走的位置
}
x = a, y = b;
}
return res;
}
};