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,然后按照螺旋形从1开始输出一个n*n矩阵。
这一题跟54.Spiral Matrix方法一样。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n));
if(n==0)
return res;
int count = n*n;
int val=1;
int row = n,col = n;
int r_r=row,c_r = col,r_d=row,c_d=col,r_l=row,c_l=col,r_u=row,c_u=col;
int i=0,j=0,direct;
bool right=true,left=false,down=false,up=false;
while(count>0){
for(direct = 1;direct<=4&&count>0;direct++){
if(direct==1){//向右
i = row-r_r;
for(j=col-c_r;j<c_r;j++){
res[i][j]=val;
count--;
val++;
}
c_r--;
r_r--;
}
if(direct==2){//向下
j = c_d-1;
for(i = row-r_d+1;i<r_d&&count>0;i++){
res[i][j]=val;
count--;
val++;
}
r_d--;
c_d--;
}
if(direct==3){//向左
i = r_l-1;
for(j=c_l-2;j>=col-c_l&&count>0;j--){
res[i][j]=val;
count--;
val++;
}
r_l--;
c_l--;
}
if(direct==4){//向上
j=col-c_u;
for(i=r_u-2;i>row-r_u&&count>0;i--){
res[i][j]=val;
count--;
val++;
}
r_u--;
c_u--;
}
}
}
return res;
}
};