螺旋矩阵(暴力算法)

题目:

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

解题思路:

      当遍历元素时,当下一个元素超出行数,或者超出列数,或者行数小于0,列数小于0,以及元素被标识了,说明方向要改变了

题解:

 public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4},
                          {5, 6, 7, 8},
                          {9, 10, 11, 12},
                          {13, 14, 15, 16}};
        List<Integer> merge = merge(matrix);
        System.err.println(merge);
    }

    public static List<Integer> merge(int[][] matrix) {
        //存储结果
        List<Integer> result = new LinkedList<>();
        //行的长度
        int rowLength = matrix.length;
        //列的长度
        int colLength = matrix[0].length;
        //标识元素
        boolean[][] booleans = new boolean[rowLength][colLength];
        //用于标识方向,分别是向右,向下,向左,向上
        int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        //计算出总元素的数量
        int totals = rowLength * colLength;
        //标识方向的下标,当下标为0就是向右,1就是向下,2向左,3向上
        int directionIndex = 0;
        //当前行数
        int row = 0;
        //当前列数
        int col = 0;
        for (int i = 1; i <= totals; i++) {
            //将元素加入集合
            result.add(matrix[row][col]);
            //标识这个元素已经被遍历了
            booleans[row][col] = true;
            //以原方向,计算下一个行数,和和下一个列数
            int nextRow = row + direction[directionIndex][0];
            int nextCol = col + direction[directionIndex][1];
            //如果超过列数,或者超过行数,或者行数小于0,列数小于0,或者已经被遍历了,说明要改变方向了,
            //每四次一个循环,所以用%4,计算方向
            if (nextRow > rowLength - 1 || nextCol > colLength - 1 || nextCol < 0 || nextRow < 0 || booleans[nextRow][nextCol]) {
                directionIndex = (directionIndex + 1) % 4;
            }
            //改变方向后,计算出行数,和列数
            row = row + direction[directionIndex][0];
            col = col + direction[directionIndex][1];
        }
        return result;

    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值