題目
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題一致福澡,權(quán)當(dāng)是把這道題練熟悉一點(diǎn)吧。
實(shí)現(xiàn)
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;
}
};
思考
無