1. 程式人生 > >牛客(19)順時針打印矩陣

牛客(19)順時針打印矩陣

for 順序 col lis 輸入 clas new RR tco

   //    題目描述
//    輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,
//    例如,如果輸入如下矩陣: 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; }

牛客(19)順時針打印矩陣