Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the Matri X in Spiral Order.
For example,
Given the following matrix:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
You should return [1,2,3,6,9,8,7,4,5]
.
Very good understanding of the idea. Each loop to traverse a circle.
Determines the coordinates (X1,Y1) of the upper-left point of the loop and the coordinates of the lower-right point (x2,y2).
The conditions for continued traversal are (x2>=x1 && y2>=y1).
is not very simple, also not easy wrong.
1 classSolution {2 Public:3vector<int> Spiralorder (vector<vector<int>>&matrix) {4vector<int>result;5 if(matrix.size () = =0|| matrix[0].size () = =0)returnresult;6 intM=matrix.size (), n=matrix[0].size ();7 intx1=0, y1=0, x2=m-1, y2=n-1;8 while(X2>=x1 & y2>=y1)9 {Ten if(X2>=x1 & y2>=y1) One { A for(inti=y1;i<=y2;i++) Result.push_back (Matrix[x1][i]); -x1++; - } the if(X2>=x1 & y2>=y1) - { - for(inti=x1;i<=x2;i++) Result.push_back (Matrix[i][y2]); -y2--; + } - if(X2>=x1 & y2>=y1) + { A for(inti=y2;i>=y1;i--) Result.push_back (Matrix[x2][i]); atx2--; - } - if(X2>=x1 & y2>=y1) - { - for(inti=x2;i>=x1;i--) Result.push_back (Matrix[i][y1]); -y1++; in } - } to returnresult; + } -};
[Leetcode] Spiral Matrix