牛客(19)顺时针打印矩阵
// 题目描述 // 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, // 例如,如果输入如下矩阵: 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. public static ArrayList<Integer> printMatrix(int[][] matrix) { ArrayList<Integer> arrayList = new ArrayList<Integer>(); int topLine = 0; int firstColumn = 0; for (int i = topLine; i < matrix.length - topLine&&firstColumn<matrix[i].length - firstColumn; i++) { for (int j = firstColumn; j < matrix[i].length - firstColumn; j++) { arrayList.add(matrix[i][j]); } for (int j = topLine + 1; j < matrix.length - topLine; j++) { if (matrix[j].length - firstColumn - 1 < firstColumn) { break; } arrayList.add(matrix[j][matrix[j].length - firstColumn - 1]); } for (int j = matrix[i].length - firstColumn - 2; j >= firstColumn; j--) { if (topLine >= matrix.length - topLine - 1) { break; } arrayList.add(matrix[matrix.length - topLine - 1][j]); } for (int j = matrix.length - topLine - 2; j > topLine; j--) { if (firstColumn >= matrix[j].length - firstColumn - 1) { break; } arrayList.add(matrix[j][firstColumn]); } topLine++; firstColumn++; } return arrayList; }