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 problem is that given an array, then a lap to read the number, and then return, relatively simple, is to pay attention to the boundary condition is good
Public classSolution { PublicList<integer> Spiralorder (int[] matrix) {List<Integer> result =NewArraylist<integer>(); if(Matrix.length = = 0) returnresult; intleft = 0,right = Matrix[0].length-1; intnum = matrix.length>matrix[0].length?matrix[0].length:matrix.length; Num= num%2 = = 0?num/2:num/2+1; for(intCircle = 0; circle<num;circle++){ if(Circle = = Matrix.length-circle-1) {//Only one row for(inti = left;i<=right;i++) Result.add (Matrix[circle][i]); returnresult; } if(left = =Right ) {//Only one column for(inti = circle;i<matrix.length-circle;i++) Result.add (Matrix[i][right]); returnresult; } for(inti = left;i<=right;i++) Result.add (Matrix[circle][i]); for(inti = circle+1;i<matrix.length-circle;i++) Result.add (Matrix[i][right]); for(inti = right-1;i>=left;i--) Result.add (matrix[matrix.length-circle-1][i]); for(inti = matrix.length-circle-2;i>circle;i--) Result.add (Matrix[i][left]); Left++; Right--; } returnresult; }}
Leetcode Spiral Matrix-----java