[LeetCode]Spiral Matrix II
Spiral Matrix II
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 ] ]
和上一题Spiral Matrix一个道理,同样的方法遍历,然后复制就OK,很好理解。
1 class Solution { 2 public: 3 vector<vector<int>> generateMatrix(int n) { 4 vector<vector<int>> result(n,vector<int>(n,0)); 5 int x1=0,y1=0,x2=n-1,y2=n-1; 6 int number=1; 7 while(x2>=x1 && y2>=y1) 8 { 9 if(x2>=x1 & y2>=y1) 10 { 11 for(int i=y1;i<=y2;i++) result[x1][i]=number++; 12 x1++; 13 } 14 if(x2>=x1 & y2>=y1) 15 { 16 for(int i=x1;i<=x2;i++) result[i][y2]=number++; 17 y2--; 18 } 19 if(x2>=x1 & y2>=y1) 20 { 21 for(int i=y2;i>=y1;i--) result[x2][i]=number++; 22 x2--; 23 } 24 if(x2>=x1 & y2>=y1) 25 { 26 for(int i=x2;i>=x1;i--) result[i][y1]=number++; 27 y1++; 28 } 29 } 30 return result; 31 } 32 };