1. 程式人生 > >演算法——轉圈列印矩陣【高頻考點】

演算法——轉圈列印矩陣【高頻考點】

【題目】 給定一個整型矩陣matrix,請按照轉圈的方式列印它。

例如: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 class PrintMatrix {
    public void printMatrix(int[][] matrix){
 //  (tR,tC)  1  2  3  4
          //  5  6  7  8
          //  9  10 11 12
          //  13 14 15 16  (dR,dC)
        int tR = 0 ;
        int tC = 0 ;
        int dR = matrix.length - 1;
        int dC = matrix[0].length - 1;
        while(tR <= dR && tC <= dC)
            //先列印外圈(1、2、3  4、8、12  16、15、14  13、9、5),
            //再列印內圈(6  7  11  10)
            printMatrix(matrix,tR++,tC++,dR--,dC--);
    }

    public void printMatrix(int[][] matrix,int tR,int tC,int dR,int dC){
        //對邊界處理
        if(tC == dC)
            for(int i = tR ; i <= dR ;i++)
                System.out.print(matrix[i][tC]+" ");
        else if(tR == dR)
            for(int i = tC ; i <= dC ;i++)
                System.out.print(matrix[tR][i]+" ");
        else{
            int curR = tR;
            int curC = tC;
            while(curC != dC)
                System.out.print(matrix[tR][curC++]+" ");
            while(curR != dR)
                System.out.print(matrix[curR++][dC]+" ");
            while(curC != tC)
                System.out.print(matrix[dR][curC--]+" ");
            while(curR != tR)
                System.out.print(matrix[curR--][tR]+" ");
        }
    }

    @Test
    public void test(){
        int [][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
        printMatrix(matrix);
    }
}