import java.util.*; public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> arr = new ArrayList<Integer>(); if(matrix.length == 0) return arr; int top = 0; int left = 0; int right = matrix[0].length - 1; int bottom = matrix.length - 1; while(left <= right && top <= bottom){ for(int col = left; col <= right; col++){ arr.add(matrix[top][col]); } if(++top > bottom) break; for(int row = top; row <= bottom; row++){ arr.add(matrix[row][right]); } if(--right < left) break; for(int col = right; col >= left; col--){ arr.add(matrix[bottom][col]); } if(--bottom < top) break; for(int row = bottom; row >= top; row--){ arr.add(matrix[row][left]); } if(++left > right) break; } return arr; } }