publicclassSolution{ public List<Integer> spiralOrder(int[][] matrix){ List<Integer> res = new LinkedList<>(); if (matrix == null || matrix.length == 0) return res; int rowEnd = matrix.length - 1, columnEnd = matrix[0].length - 1, rowBegin = 0, columnBegin = 0; while (rowBegin <= rowEnd && columnBegin <= columnEnd) { // top, left to right for (int i = columnBegin; i <= columnEnd; i++) { res.add(matrix[rowBegin][i]); } rowBegin++; // right, top to bottom for (int j = rowBegin; j <= rowEnd; j++) { res.add(matrix[j][columnEnd]); } columnEnd--; // bottom, right to left if (rowBegin <= rowEnd) { for (int k = columnEnd; k >= columnBegin; k--) { res.add(matrix[rowEnd][k]); } } // left, bottom to top rowEnd--; if (columnBegin <= columnEnd) { for (int l = rowEnd; l >= rowBegin; l--) { res.add(matrix[l][columnBegin]); } } columnBegin++; } return res; } }