Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
- 模拟就行了
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int i=0,k=1;
while(k<=n*n){
int j=i;
while(k<=n*n&&j<n-i)res[i][j++]=k++;j--;i++;
while(k<=n*n&&i<=j)res[i++][j]=k++;i--;j--;
while(k<=n*n&&j>=n-i-1)res[i][j--]=k++;j++;i--;
while(k<=n*n&&i>j)res[i--][j]=k++;i++;j++;
}
return res;
}
};