题目:
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ret;
for (int i = 0; i < n; i++) {
ret.push_back(vector<int>(n, 0));
}
if(n == 0)
return ret;
int x1 = 0;
int y1 = 0;
int x2 = n - 1;
int y2 = n - 1;
int cnt = 1;
while (x1 <= x2 && y1 <= y2) {
for (int i = x1; i <= x2; i++)
ret[y1][i] = cnt++;
y1++;
for (int i = y1; i <= y2; i++)
ret[i][x2] = cnt++;
x2--;
for (int i = x2; i >= x1; i--)
ret[y2][i] = cnt++;
y2--;
for (int i = y2; i >= y1; i--)
ret[i][x1] = cnt++;
x1++;
}
return ret;
}
};