順時針打印矩陣

劍指offer有一道關於順時針打印矩陣的面試題,感覺挺有意思的,題意很簡單,輸入一個矩陣,順時針打印每個數字。
例如輸入以下矩陣

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 。本體的關鍵是要把握好邊界條件,每次從左上角的開始打印。

package sxd.learn.java.questions;

public class PrintMatrix {
    private int r_upper_threshold;
    private int c_upper_threshold;
    private int r_lower_threshold;
    private int c_lower_threshold;

    public static void main(String[] args) {
        new PrintMatrix().run();
    }

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

        int[][] matrix2 = {
                {1, 2, 3, 4},
                {2, 3, 4, 5},
                {5, 6, 7, 8},
        };

        int[][] matrix3 = {
                {1}, {2}, {3}, {4}
        };

        int[][] matrix4 = {
                {1, 2},
                {5, 6},
                {3, 4},
                {7, 8},
        };

        int[][] matrix5 = {
                {1, 2, 3, 4}
        };

        printMatirxClockwisely(matrix5, 1, 4);
    }

    public void printMatirxClockwisely(int[][] matrix, int rows, int columns) {
        r_upper_threshold = rows;
        c_upper_threshold = columns;
        r_lower_threshold = -1;
        c_lower_threshold = -1;

        int startRows = 0;
        int startCols = 0;

        while (startRows < r_upper_threshold && startCols < c_upper_threshold) {
            printMatrixInCircle(matrix, startRows, startCols);
            r_lower_threshold++;
            c_lower_threshold++;
            r_upper_threshold--;
            c_upper_threshold--;
            startRows++;
            startCols++;
        }
    }

    private void printMatrixInCircle(int[][] matrix ,int r, int c){
        while (c < c_upper_threshold){
            System.out.print(matrix[r][c] + " ");
            c++;
        }

        c--;
        r++;
        while (r < r_upper_threshold) {
            System.out.print(matrix[r][c] + " ");
            r++;
        }

        r--;
        c--;
        while (c > c_lower_threshold && r != r_lower_threshold + 1) {
            System.out.print(matrix[r][c] + " ");
            c--;
        }

        c++;
        r--;
        while (r > r_lower_threshold + 1 && c != c_upper_threshold - 1) {
            System.out.print(matrix[r][c] + " ");
            r--;
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章