Description
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input:
3
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
分析
- 這道題的思路很直接,按照規則順時針填數就行了,這裡注意邊界的問題,從左上到右上周遊完以後,行的起始行要+1,從右上到右下的周遊完以後,列的結束行要-1,從右下角到左下角周遊完以後,結束行要-1,從左下角到左上角周遊的時候,起始列要+1.
代碼
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n,0));
int row=0;
int col=0;
int rows=n-1;
int cols=n-1;
int cnt=1;
while(row<=rows&&col<=cols){
for(int i=col;i<=cols;i++){
res[row][i]=cnt;
cnt++;
}
row++;
for(int i=row;i<=rows;i++){
res[i][cols]=cnt;
cnt++;
}
cols--;
for(int i=cols;i>=col;i--){
res[rows][i]=cnt;
cnt++;
}
rows--;
for(int i=rows;i>=row;i--){
res[i][col]=cnt;
cnt++;
}
col++;
}
return res;
}
};