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] .
This problem thought for a long time did not think up, can only blame oneself too lazy, lazy to think to try, should calm down heart to not too impetuous.
There are four kinds of cases, from left to right, top to bottom, right to left, and bottom up.
Careful observation found that it was possible to make use of changes in Rowresult and Columnresult.
Put the code below, be sure to note that the
int row = Matrix.length;
int column = Matrix[0].length; before judging if the matrix is empty. So that the column does not go wrong.
The code is as follows:
public class Solution {public list<integer> spiralorder (int[][] matrix) {list<integer> Listresult = new Arraylist<integer> (); if (Matrix = = NULL | | matrix.length==0) {return listresult; } int row = Matrix.length; int column = Matrix[0].length; int rowNumber = 0; int columnnumber = 0; while (row>0&&column>0) {if (row = = 1) {for (int i = 0;i<column;i++) {Listresult.add (ma trix[rownumber][columnnumber++]); } break; } else {if (column = = 1) {for (int i = 0;i<row;i++) {Listresult.add (matrix[rownumber++][ ColumnNumber]); } break; }} for (int i = 0;i<column-1;i++) {listresult.add (matrix[rownumber][columnnumber++]); }//columnnumber = columnNumber-1; for (int i = 0;i<row-1;i++) {listresult.add (Matrix[rownumber++][columnnumber]); }//rownumber = rowNumber-1; for (int i = 0;i<column-1;i++) {listresult.add (matrix[rownumber][columnnumber--]); }//columnnumber = ColumnNumber + 1; for (int i =0;i<row-1;i++) {Listresult.add (Matrix[rownumber--][columnnumber]); } rownumber++; columnnumber++; row = Row-2; column = Column-2; } return Listresult; }}
Leetcode's Spiral Matrix