problem:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]按顺序编写即可,以每行的(i,i)为起点
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result(n, vector<int>(n));
if(n == 0)
return result;
int layer = (n + 1) / 2;
int initial_num = 1;
for(int i=0; i<layer; i++)
{
//row i
int first = initial_num;
for(int j=i; j<n-i; j++)
{
result[i][j] = first + j - i;
}
//col n-i-1
first = result[i][n-i-1];
for(int j=i+1; j<n-i; j++)
{
result[j][n-i-1] = first + j - i;
}
//row n-i-1
first = result[n-i-1][n-i-1];
for(int j=n-i-1-1; j>=i; j--)
{
result[n-i-1][j] = first + n - i - 1 - j;
}
//col i
first = result[n-1-i][i];
for(int j=n-i-1-1; j>i; j--)
{
result[j][i] = first + n - i - 1 - j;
}
initial_num += (n-i*2-1)*4;
}
return result;
}
};