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