题目:
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 ] ]
解析:填充 n * n 螺旋形矩阵
与上道题类似
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int> > res(n,vector<int>(n,-1));
vector<vector<int> > tmp;
if(n == 0) return tmp;
int r1 = 0, r2 = n -1;
int c1 = 0, c2 = n -1;
int cnt = 0;
while( r1 <= r2 && c1 <= c2)
{
for(int c = c1; c <= c2; c++)
{
res[r1][c] = ++cnt;
}
for(int r = r1 + 1; r <= r2; r++)
{
res[r][c2] = ++cnt;
}
if(r1 < r2 && c1 < c2)
{
for(int c = c2 - 1; c >= c1; c--)
{
res[r2][c] = ++cnt;
}
for(int r = r2 -1 ; r > r1; r--)
{
res[r][c1] = ++cnt;
}
}
r1++;
r2--;
c1++;
c2--;
}
return res;
}
};