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 ]
]
旋转式写矩阵,最直观的方式就是一个边一个边的写矩阵。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n));
int l=0,r=n-1,u=0,d=n-1;
int num=1;
while(true){
for(int col=l;col<=r;col++)
res[u][col]=num++;
if(++u>d)
break;
for(int raw=u;raw<=d;raw++)
res[raw][r]=num++;
if(--r<l)
break;
for(int col=r;col>=l;col--)
res[d][col]=num++;
if(--d<u)
break;
for(int raw=d;raw>=u;raw--)
res[raw][l]=num++;
if(++l>r)
break;
}
return res;
}