54. Spiral Matrix 发表于 2022-01-26 123456789101112131415161718192021222324252627282930313233343536373839class Solution { public List<Integer> spiralOrder(int[][] matrix) { int m = matrix.length, n = matrix[0].length; List<Integer> list = new ArrayList<>(m * n); int startRowIndex = 0, endRowIndex = m - 1; int startColIndex = 0, endColIndex = n - 1; while (true) { // 注意 colIndex 从 startColIndex 开始,不要从 0 开始 for (int colIndex = startColIndex; colIndex <= endColIndex; colIndex++) { list.add(matrix[startRowIndex][colIndex]); } if (++startRowIndex > endRowIndex) { break; } for (int rowIndex = startRowIndex; rowIndex <= endRowIndex; rowIndex++) { list.add(matrix[rowIndex][endColIndex]); } if (--endColIndex < startColIndex) { break; } for (int colIndex = endColIndex; colIndex >= startColIndex; colIndex--) { list.add(matrix[endRowIndex][colIndex]); } if (--endRowIndex < startRowIndex) { break; } for (int rowIndex = endRowIndex; rowIndex >= startRowIndex; rowIndex--) { list.add(matrix[rowIndex][startColIndex]); } if (++startColIndex > endColIndex) { break; } } return list; }} 注意四个边界判断,需要超出才跳出循环,等于时是可以打印的,因为定义的行列变量是可打印的边界,等于时表明该 行/列 还没有被打印。 Reference54. Spiral Matrix剑指 Offer 29. 顺时针打印矩阵