Leetcode:59. Spiral Matrix II
Description
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
Example
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路
- 没啥好说的,一圈一圈的打印
代码
cclass Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int start = 0;
int sum = 1;
while(start * 2 < n){
generate(res, n, start, sum);
start++;
}
return res;
}
void generate(vector<vector<int>>& res, int n, int start, int &count){
int endCol = n - start - 1;
int endRow = n - start - 1;
for(int i = start; i <= endCol; ++i)
res[start][i] = count++;
if(endRow > start){
for(int i = start + 1; i <= endRow; ++i)
res[i][endCol] = count++;
}
if(endCol > start){
for(int i = endCol - 1; i >= start; --i)
res[endRow][i] = count++;
}
if(endRow > start && endCol > start){
for(int i = endRow - 1; i > start; --i)
res[i][start] = count++;
}
}
};