Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
ps:判断好边界即可,n为偶数或者奇数,都是走n/2圈。
n为奇数的时候,要记得给n*n矩阵正中间剩下那个值赋值。
代码:
class Solution{ private: int num; public: void doit(int start,int end,vector<vector<int>>& res){ if(start>=end) return; int col;int row;col=row=end; for (int i=start;i<=col;++i) res[start][i]=num++; for (int j=start+1;j<=row;++j) res[j][col]=num++; for (int m=col-1;m>=start;--m) res[row][m]=num++; for (int n=row-1;n>=start+1;--n) res[n][start]=num++; return; } vector<vector<int> > generateMatrix(int n) { vector<int> temp(n,0); vector<vector<int> > res(n,temp); if(n<=0) return res; num=1; int time=n/2; for (int i=0;i<time;++i) { doit(i,n-1-i,res); } if(n==1) res[0][0]=1; else if(n>=3&&n&0x1==1) res[time][time]=n*n; return res; } };