classSolution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = newArrayList<>(); // corner case if (matrix == null || matrix.length == 0) { return res; }
// normal case inttop=0; intbottom= matrix.length - 1; intleft=0; intright= matrix[0].length - 1; while (top <= bottom && left <= right) { // left to right for (inti= left; i <= right; i++) { res.add(matrix[top][i]); } top++;
// top to bottom for (inti= top; i <= bottom; i++) { res.add(matrix[i][right]); } right--;
// right to left if (top <= bottom) { for (inti= right; i >= left; i--) { res.add(matrix[bottom][i]); } bottom--; }
// bottom to top if (left <= right) { for (inti= bottom; i >= top; i--) { res.add(matrix[i][left]); } left++; } } return res; } }