🍕🎉🥓🎊🚗🐷😱❤😀❣🥙🎇🕵️♀️😎🎑🎁🎉😚🎇
题目:
- 给你一个正整数
n
,生成一个包含1
到 n 2 n^2 n2 所有元素,且元素按顺时针顺序螺旋排列的n x n
正方形矩阵matrix
。
C++
class Solution {
public:
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
for(int x = 0, y = 0, i = 0, d = 1; i < n * n; i++){
res[x][y] = i + 1;
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;
}
};