classSolution { public List<Integer> spiralOrder(int[][] matrix) { if (matrix.length == 0) returnnewArrayList<Integer>(); intl=0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1, x = 0; Integer[] res = newInteger[(r + 1) * (b + 1)]; while (true) { for (inti= l; i <= r; i++) res[x++] = matrix[t][i]; // left to right if (++t > b) break; for (inti= t; i <= b; i++) res[x++] = matrix[i][r]; // top to bottom if (l > --r) break; for (inti= r; i >= l; i--) res[x++] = matrix[b][i]; // right to left if (t > --b) break; for (inti= b; i >= t; i--) res[x++] = matrix[i][l]; // bottom to top if (++l > r) break; } return Arrays.asList(res); } }