题目
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
分析
思路基本可54题一致,权当是把这道题练熟悉一点吧。
实现
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if(n==0) return {};
vector<vector<int>> ans(n, vector<int>(n, 0));
int layers=(n-1)/2, x=0, y=0, i=1;
for(int l=0; l<=layers; l++){
while(y<=n-l-1){
ans[x][y] = i;
y++; i++;
}
y--; x++;
while(x<=n-l-1){
ans[x][y] = i;
x++; i++;
}
x--; y--;
while(y>=l){
ans[x][y] = i;
y--; i++;
}
y++; x--;
while(x>=l+1){
ans[x][y] = i;
x--; i++;
}
x++; y++;
}
return ans;
}
};
思考
无