题目:
Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
For example,
Given n =3,
You should return the following matrix:
[
[ 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,0));//创建二维数组
int i=0,j=0,num=1;
while(num<n*n+1)
{
while(j<n&&res[i][j]==0)
{
res[i][j]=num;
j++;
num++;
}
j--;
i++;
while(i<n&&res[i][j]==0)
{
res[i][j]=num;
i++;
num++;
}
i--;
j--;
while(j>=0&&res[i][j]==0)
{
res[i][j]=num;
j--;
num++;
}
j++;
i--;
while(i>=0&&res[i][j]==0)
{
res[i][j]=num;
i--;
num++;
}
i++;
j++;
}
return res;
}
};