Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix 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]
.
public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { // Start typing your Java solution below // DO NOT write main() function ArrayList<Integer> list = new ArrayList<Integer>(); if (matrix.length==0) return list; int row = matrix.length; int col = matrix[0].length; int top =0; int bottom = row-1; int left = 0; int right = col -1; while(top < bottom && left < right){ for (int j = left ;j<=right;j++){ list.add(matrix[top][j]); } ++top; for(int j = top; j<=bottom;j++){ list.add(matrix[j][right]); } right--; for(int i = right;i>= left;i--){ list.add(matrix[bottom][i]); } bottom--; for(int k = bottom;k>= top;k--){ list.add(matrix[k][left]); } left++; } if(left<right&&top == bottom){ for(int i = left;i <=right; i++){ list.add(matrix[top][i]);//long square } } if(top<bottom&& left == right){ for(int i = top; i <= bottom;i++){ list.add(matrix[i][left]);//len square } } if(top == bottom && left == right){ list.add(matrix[top][left]); } return list; } }