顺时针打印矩阵

剑指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--;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值