【剑指Offer】顺时针打印矩阵 Posted on 2017-05-14 | In Algorithm , 剑指Offer 题目输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。 实现1234567891011121314151617181920212223242526272829303132333435363738public ArrayList<Integer> printMatrix(int[][] matrix) { int rows = matrix.length; int columns = matrix[0].length; int start = 0; ArrayList<Integer> result = new ArrayList<>(); while (2 * start < rows && 2 * start < columns){ printMatrixInCircle(result, matrix, start); start++; } return result;}private void printMatrixInCircle(ArrayList<Integer> result, int[][] matrix, int start){ int rows = matrix.length; int columns = matrix[0].length; int endX = columns - start - 1; int endY = rows - start - 1; for (int i = start; i <= endX; i++) result.add(matrix[start][i]); if (start < endY){ for (int i = start + 1; i <= endY; i++) result.add(matrix[i][endX]); } if (start < endX && start < endY){ for (int i = endX - 1; i >= start; i--) result.add(matrix[endY][i]); } if (start < endY - 1 && start < endX){ for (int i = endY - 1; i > start; i--) result.add(matrix[i][start]); }}