1. 程式人生 > >《程式設計師程式碼面試指南》 給定一個整型矩陣 matrix 請按照轉圈的方式列印它

《程式設計師程式碼面試指南》 給定一個整型矩陣 matrix 請按照轉圈的方式列印它

題目

給定一個整型矩陣 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。

解答:

這裡介紹一種矩陣處理的方式,該方式不僅可用於這道題,還適合很多其他的面試題,這就是矩陣分圈處理。

在矩陣中左上角的座標(tR,tC)和右下腳的座標(dR,dC)就可以表示 一個子矩陣,比如,題目中的矩陣,當(tR,tC)= (0,0)、(dR,dC) = (3,3)時,表示的子矩陣就是整個矩陣,那麼這個矩陣的最外層就是:

1    2    3    4

5                8

9                12

13 14  15   16

打印出來的結果為:1,2,3,4,8,12,16,15,14,13,9,5。接下來令tR和tC加1,即(tR,tC)=(1,1)令dR和dC減1,即(dR,dC)=(2,2),此時表示的矩陣為:

6    7

10  11

打印出來為:6,7,11,10。

重複如上操作。

如果發現左上角的座標跑到右下角座標的右方或是下方,整個過程結束。

public class CirclePrintMatrix {
    public static void spiralOrderPrint(int[][] matrix){
        int tR = 0;
        int tC = 0;
        int dR = matrix.length - 1;
        int dC = matrix[0].length - 1;
        while(tR <= dR && tC <= dC){
            printEdge(matrix, tR++, tC++, dR--, dC--);
        }
    }
    public static  void printEdge(int[][] matrix, int tR, int tC, int dR, int dC){
        //只有一行
        if(tR == dR){
            for(int i = tC; i <= dC; i++){
                System.out.print(matrix[tR][i] +" ");
            }
            //只有一列
        }else if(tC == dC) {
            for (int i = tR; i <= dR; i++) {
                System.out.print(matrix[i][tC] + " ");
            }
        }else{//一般情況
            int curC = tC;
            int curR = tR;
            while(curC != dC){
                System.out.print(matrix[tR][curC] + " ");
                curC++;
            }
            while(curR!= dR){
                System.out.print(matrix[curR][dC] + " ");
                curR++;
            }
            while(curC != tC){
                System.out.print(matrix[dR][curC] + " ");
                curC--;
            }
            while (curR != tR){
                System.out.print(matrix[curR][tC] + " ");
                curR--;
            }
        }

    }
    public static void main(String[] args) {
        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
        spiralOrderPrint(matrix);

    }
}

參考資料:《程式設計師面試程式碼指南》左程雲 著