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 ] ]
没什么算法可言,模拟数据写入顺序依次写入即可
AC Code:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> rst(n, vector<int>(n , -1));
int num = 1;
int i = 0;
int j = 0;
int pi,pj;
int p = 0;//0: right , 1: down, 2: left, 3: up
if(n == 0)
return vector<vector<int>>();
rst[0][0] = 1;
while(num < n*n)
{
switch(p)
{
case 0:
pi = i;
pj = j+1;
break;
case 1:
pi = i+1;
pj = j;
break;
case 2:
pi = i;
pj = j-1;
break;
case 3:
pi = i-1;
pj = j;
break;
default:
break;
}
if(pi<0 || pj<0 || pi>=n || pj>= n)
{
p = (++p)%4;
}
else if(rst[pi][pj] != -1)
{
p = (++p)%4;
}
else
{
i = pi;
j = pj;
num++;
rst[i][j] = num;
}
}
return rst;
}
};