顺时针遍历方阵

本文介绍了如何顺时针遍历一个方阵,主要思路是通过递归实现,先遍历最外层,然后逐步收缩至内圈。在递归过程中,结束条件为中间只剩一个或四个元素。作者在面试中遇到此题并进行了重述和梳理。

如题:顺时针遍历一个方阵

昨天去面试,考到了这个题,当时写的不是特别好,回到家重新梳理了一下

思路就是采用递归遍历,先遍历最外圈,然后四角收缩,遍历内圈矩阵,递归的终止条件有两种,一种是中间剩一个元素,一种是中间剩四个元素

代码如下

package r.w.practice;

public class MatrixTraverser {

    public static void main(String[] args) {

        int[][] matrix = new int[][]{
                {0, 1, 2, 3},
                {11, 12, 13, 4},
                {10, 15, 14, 5},
                {9, 8, 7, 6}
        };
        new MatrixTraverser().traverse(matrix);
    }

    private void traverse(int[][] matrix) {

        if (matrix == null
                || matrix.length == 0
                || matrix.length != matrix[0].length) {
            throw new IllegalArgumentException("matrix is not valid");
        }
        final int length = matrix.length;
        Point leftUp = new Point(0, 0);
        Point rightUp = new Point(0, length - 1);
        Point rightBottom = new Point(length - 1, length - 1);
        Point leftBottom = new Point(length - 1, 0);
        _traverse(matrix, leftUp, rightUp, rightBottom, leftBottom);
    }

    private void _traverse(int[][] matrix, Point leftUp, Point rightUp, Point rightBottom, Point leftBottom) {

        if (leftUp.col == rightUp.col) {
            System.out.println(matrix[leftUp.row][leftUp.col]);
            return;
        }
        if (rightUp.col - leftUp.col == 1) {
            System.out.println(matrix[leftUp.row][leftUp.col]);
            System.out.println(matrix[rightUp.row][rightUp.col]);
            System.out.println(matrix[rightBottom.row][rightBottom.col]);
            System.out.println(matrix[leftBottom.row][leftBottom.col]);
            return;
        }
        for (int col = leftUp.col; col <= rightUp.col; col++) {
            System.out.println(matrix[leftUp.row][col]);
        }
        for (int row = rightUp.row + 1; row <= rightBottom.row; row++) {
            System.out.println(matrix[row][rightUp.col]);
        }
        for (int col = rightBottom.col - 1; col >= leftBottom.col; col--) {
            System.out.println(matrix[rightBottom.row][col]);
        }
        for (int row = leftBottom.row - 1; row > leftUp.row; row--) {
            System.out.println(matrix[row][leftBottom.col]);
        }
        _traverse(matrix,
                new Point(leftUp.row + 1, leftUp.col + 1),
                new Point(rightUp.row + 1, rightUp.col - 1),
                new Point(rightBottom.row - 1, rightBottom.col - 1),
                new Point(leftBottom.row - 1, leftBottom.col + 1)
        );
    }

    class Point {

        private int row;

        private int col;

        Point(int row, int col) {

            this.row = row;
            this.col = col;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值