title :
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]
.
The following:
This problem is a realization problem.
Consider 2 initial conditions, if the matrix has only one row or column, then you do not need to rotate, then output.
All other situations need to be in circles: from left to right, from top to bottom, right to left, bottom to top. Loop from the big circle to the small circle in turn.
The code is as follows:
1 PublicArraylist<integer> Spiralorder (int[] matrix) {2arraylist<integer> result =NewArraylist<integer>();3 if(Matrix = =NULL|| Matrix.length = = 0)4 returnresult;5 6 intm =matrix.length;7 intn = matrix[0].length;8 9 intX=0; Ten intY=0; One A while(M>0 && n>0){ - - //if one row/column left, no circle can be formed the if(m==1){ - for(inti=0; i<n; i++){ -Result.add (matrix[x][y++]); - } + Break; -}Else if(n==1){ + for(inti=0; i<m; i++){ AResult.add (matrix[x++][y]); at } - Break; - } - - //below, process a circle - in //Top-move Right - for(inti=0;i<n-1;i++) toResult.add (matrix[x][y++]); + - //Right-move Down the for(inti=0;i<m-1;i++) *Result.add (matrix[x++][y]); $ Panax Notoginseng //Bottom-move Left - for(inti=0;i<n-1;i++) theResult.add (matrix[x][y--]); + A //Left-move up the for(inti=0;i<m-1;i++) +Result.add (matrix[x--][y]); - $X + +; $y++; -M=m-2; -N=n-2; the } - Wuyi returnresult; the}
Reference:http://www.cnblogs.com/springfor/p/3887890.html
*spiral Matrix