zoukankan      html  css  js  c++  java
  • Medium | LeetCode 54 | 剑指 Offer 29. 顺时针打印矩阵 | 矩阵 + DFS

    剑指 Offer 29. 顺时针打印矩阵

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

    示例 1:

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

    示例 2:

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

    限制:

    • 0 <= matrix.length <= 100
    • 0 <= matrix[i].length <= 100

    常规的DFS矩阵遍历问题。只需要定义四个方向, 这个方向的下个元素不可达的时候, 切换方向就可以了.

    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0) {
            return new int[0];
        }
        // 螺旋矩阵的遍历方向
        int[][] direction = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // 上, 右, 下, 左 四个方向
        // 访问数组
        boolean[][] visited = new boolean[matrix.length][matrix[0].length];
        int[] res = new int[matrix.length * matrix[0].length];
        int index = 0;
        // 设定初始方向为向右
        int row = 0, col = 0, dire = 1;
        for (int i = 0; i < matrix.length * matrix[0].length; i++) {
            // 访问当前位置
            res[index++] = matrix[row][col];
            visited[row][col] = true;
            // 下一个遍历的位置
            int newx = row + direction[dire][0];
            int newy = col + direction[dire][1];
            // 如果下一个遍历的位置已经访问或者不可达, 则切换到下一个方向
            if (!(newx >= 0 && newx < matrix.length && newy >= 0 && newy < matrix[0].length) || visited[newx][newy]) {
                dire = (dire + 1) % 4;
            }
            row += direction[dire][0];
            col += direction[dire][1];
        }
        return res;
    }
    
  • 相关阅读:
    baremetal node & openstack hypervisor &openstack flavor
    bridge fdb vxlan nolearning
    bridge fdb 与vxlan
    FRRouting Architecture
    bridge fdb Command Output
    while循环和until语句
    Python私有属性和私有方法
    python面向对象封装案例2
    Python面向对象封装案例
    Python类和对象
  • 原文地址:https://www.cnblogs.com/chenrj97/p/14288956.html
Copyright © 2011-2022 走看看