转圈打印矩阵

打印矩阵的思路:

先找出矩阵的左上顶点和右下顶点,然后转圈打印四条边,打印一圈后,左上顶点和右下顶点同时往内移动一个单位,在转圈打印

public class PrintMatrixInSpiral {
    
    public static  void print(int [][] matrix ) {
        int tR = 0;
        int tC = 0;
        int bR = matrix.length - 1;
        int bC = matrix[0].length - 1;
        while (tR <= bR && tC <= bC) {
            printEdge(matrix, tR++, tC++, bR--, bC--);
        }
    }
    

    public static void printEdge(int[][] m, int tR, int tC, int bR, int bC) {
        if (tR == bR) { //行相等了,打印整行
            for (int i = tC; i <= bC; i++) {
                System.out.print(m[tR][i] + " ");
            }
        } else if (tC == bC) { //列相等,打印整列
            for (int i = tR; i <= bR; i++) {
                System.out.print(m[i][tC] + " ");
            }
        } else { //打印四条边,打印每条边时,注意结束元素的下标
            int curC = tC;
            int curR = tR;
            while (curC != bC) {
                System.out.print(m[tR][curC] + " ");
                curC++;
            }
            while (curR != bR) {
                System.out.print(m[curR][bC] + " ");
                curR++;
            }
            while (curC != tC) {
                System.out.print(m[bR][curC] + " ");
                curC--;
            }
            while (curR != tR) {
                System.out.print(m[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 } };
        print(matrix);
    }
}

 

posted @ 2019-10-06 21:12  踏月而来  阅读(214)  评论(0编辑  收藏  举报