classSolution{ public List < Integer > spiralOrder(int[][] matrix) { List ans = new ArrayList(); if (matrix.length == 0) return ans; int top = 0, down = matrix.length - 1; int left = 0, right = matrix[0].length - 1; while (top <= down && left <= right) { for (int i = left; i <= right; i++) ans.add(matrix[top][i]); for (int i = top + 1; i <= down; i++) ans.add(matrix[i][right]); if (top < down && left < right) { for (int i = right - 1; i > left; i--) ans.add(matrix[down][i]); for (int i = down; i > top; i--) ans.add(matrix[i][left]); } top++; down--; left++; right--; } return ans; } }