顺时针打印矩阵

2018-08-29  本文已影响0人  stoneyang94

题目:顺时针打印矩阵(算法课第四课)

对于一个矩阵,请设计一个算法从左上角(mat[0][0])开始,顺时针打印矩阵元素。
给定int矩阵mat,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。

举例

输入矩阵:

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 PrintMatrixSpiral {
    public static void spiralMatrix(int[][] matrix) {
        int tR = 0;// top row 
        int tC = 0;// top column
        int dR = matrix.length - 1;//down row
        int dC = matrix[0].length - 1;//down column
        while (tR <= dR && tC <= dC) {//有等于号
            printEdge(matrix, tR++, tC++, dR--, dC--);
        }
    }

    public static void printEdge(int[][] m, int tR, int tC, int dR, int dC) {
        if (tR == dR) {// 只有一行的时候
            for (int i = tC; i <= dC; i++) {
                System.out.print(m[tR][i] + " ");
            }
        } else if (tC == dC) {// 只有一列的时候
            for (int i = tR; i <= dR; i++) {
                System.out.print(m[i][tC] + " ");
            }
        } else {
            int curC = tC;
            int curR = tR;
            while (curC != dC) {// 从左到右打印
                System.out.print(m[tR][curC] + " ");
                curC++;
            }
            while (curR != dR) {// 从上往下打印
                System.out.print(m[curR][dC] + " ");
                curR++;
            }
            while (curC != tC) {// 从右往左打印
                System.out.print(m[dR][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 } };
        spiralMatrix(matrix);
    }
}

输出:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 
上一篇 下一篇

猜你喜欢

热点阅读