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]]
And the previous question spiral matrix A truth, the same way traversal, and then copy on OK, very good understanding.
1 classSolution {2 Public:3vector<vector<int>> Generatematrix (intN) {4vector<vector<int>> Result (n,vector<int> (n,0));5 intx1=0, y1=0, x2=n-1, y2=n-1;6 intNumber=1;7 while(X2>=x1 && y2>=y1)8 {9 if(X2>=x1 & y2>=y1)Ten { One for(inti=y1;i<=y2;i++) result[x1][i]=number++; Ax1++; - } - if(X2>=x1 & y2>=y1) the { - for(inti=x1;i<=x2;i++) result[i][y2]=number++; -y2--; - } + if(X2>=x1 & y2>=y1) - { + for(inti=y2;i>=y1;i--) result[x2][i]=number++; Ax2--; at } - if(X2>=x1 & y2>=y1) - { - for(inti=x2;i>=x1;i--) result[i][y1]=number++; -y1++; - } in } - returnresult; to } +};
[Leetcode] Spiral Matrix II