classSolution{ publicint[] spiralOrder(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { returnnewint[0]; } int rows = matrix.length, cols = matrix[0].length; int[] res = newint[rows * cols]; int up = 0, down = rows - 1; int left = 0, right = cols - 1; int index = 0; while (up <= down && left <= right) { for (int u = left; u <= right; u++) { res[index++] = matrix[up][u]; } for (int r = up + 1; r <= down; r++) { res[index++] = matrix[r][right]; } if (up < down && left < right) { for (int d = right - 1; d > left; d--) { res[index++] = matrix[down][d]; } for (int l = down; l > up; l--) { res[index++] = matrix[l][left]; } } up++; left++; down--; right--; } return res; } }