[leetCode]542. 01 矩阵

BFS

将所有的0构建为一个超级0,用超级0到终点的最短路径等价于多个源点到终点的最短路径

class Solution {
    // 定义一个方向数组
    static int[][] dirs = new int[][]{{1,0}, {0,1}, {-1, 0}, {0, -1}};

    public int[][] updateMatrix(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] ans = new int[m][n];
        // 已经走过的网格
        boolean[][] seen = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        // 将所有0添加到初始队列中
        for (int row = 0; row < m; row++) {
            for (int col = 0; col < n; col++) {
                if (matrix[row][col] == 0) {
                    queue.offer(new int[]{row, col});
                    seen[row][col] = true;
                }
            }
        }

        // 广度优先搜索
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            int x = cell[0], y = cell[1];
            for (int[] dir : dirs) {
                int nextX = x + dir[0];
                int nextY = y + dir[1];
                if (nextX < 0 || nextX > m - 1 || nextY < 0 || nextY > n - 1 || seen[nextX][nextY])
                    continue;
                ans[nextX][nextY] = ans[x][y] + 1;
                queue.offer(new int[]{nextX, nextY});
                seen[nextX][nextY] = true;
            }
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13859893.html