spiral-matrix-ii
2019-07-24 本文已影响0人
DaiMorph
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int>>res(n,vector<int>(n));
if(n==0)return res;
int num=1;
int left=0,right=n-1,up=0,down=n-1;
while(left<=right&&up<=down)
{
for(int j=left;j<=right;j++)res[up][j]=num++;
for(int i=up+1;i<=down;i++)res[i][right]=num++;
for(int j=right-1;j>=left&&up!=down;j--)res[down][j]=num++;
for(int i=down-1;i>up&&left!=right;i--)res[i][left]=num++;
up++,down--,left++,right--;
}
return res;
}
};