/** * 题目: * 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, * 例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 * 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. */ import java.util.ArrayList; public class P163_PrintMatrixByClockwise { ArrayList<Integer> result = new ArrayList<>(); public ArrayList<Integer> PrintMatrixByClockwise(int[][] matrix) { if (matrix == null || matrix.length == 0) { return result; } //矩阵的行数 int rows = matrix.length; //矩阵的列数 int columns = matrix[0].length; for(int start=0;rows>2*start&&columns>2*start;start++){ PrintMatrix(matrix, rows, columns, start); } return result; } public void PrintMatrix(int[][] matrix, int rows, int columns, int start) { int endRows = columns - 1 - start; int endColumns = rows - 1 - start; //从左到右打印一行 for (int i = start; i <= endRows; i++) { result.add(matrix[start][i]); } //从上到下打印一列 if (endColumns > start) { for (int i = start + 1; i <= endColumns; i++) { result.add(matrix[i][endRows]); } } //从右向左打印一行 if (endRows > start && endColumns > start) { for (int i = endRows - 1; i >= start; i--) { result.add(matrix[endColumns][i]); } } //从下向上打印一列 if (endColumns > start && endRows > start) { for (int i = endColumns - 1; i > start; i--) { result.add(matrix[i][start]); } } } public static void main(String[] args) { int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; P163_PrintMatrixByClockwise test = new P163_PrintMatrixByClockwise(); ArrayList result = test.PrintMatrixByClockwise(matrix); System.out.print(result); } }
剑指offer:顺时针打印矩阵(java)
最新推荐文章于 2023-03-06 23:44:20 发布