1 class Solution 2 { 3 public: 4 vector> generateMatrix(int n) 5 { 6 vector > res(n,vector (n,0)); 7 int right=n-1,down=n-1; 8 int left=0,up=0,k=1; 9 int lim=n*n;10 while(k<=lim)11 {12 for(int x=left;x<=right;x++)13 res[up][x]=k++;14 up++;15 for(int y=up;y<=down;y++)16 res[y][right]=k++;17 right--;18 for(int x=right;x>=left;x--)19 res[down][x]=k++;20 down--;21 for(int y=down;y>=up;y--)22 res[y][left]=k++;23 left++;24 }25 return res;26 }27 };
和螺旋输出相反,这个直接螺旋填写即可