【BFS】LeetCode 542. 01 矩阵

题目链接

542. 01 矩阵

思路

题目让求1到0的距离,其实可以转换成求0到1的距离,将所有的0作为源结点放入队列进行BFS。

BFS本质上就是从源点开始的搜索算法,本题只不过是所有的0都是源点,即多源点,将所有源点放入队列就行。

如果0的旁边没有1,则不会对其周围进行访问;如果0的周围有1,则会访问1的坐标,并修改其中的值为距离。

代码

class Solution {
    public int[][] updateMatrix(int[][] mat) {
        Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
        boolean[][] visited = new boolean[mat.length][mat[0].length];

        for(int i = 0; i < mat.length; i++){
            for(int j = 0; j < mat[i].length; j++){
                if(mat[i][j] == 0){
                    queue.offer(new Pair<>(i, j));
                    visited[i][j] = true;
                }
            }
        }

        int[] dx = new int[]{1, 0, -1, 0};
        int[] dy = new int[]{0, 1, 0, -1};
        while(!queue.isEmpty()){
            Pair<Integer, Integer> currentPos = queue.remove();
            for(int i = 0; i < 4; i++){
                int nextX = currentPos.getKey() + dx[i];
                int nextY = currentPos.getValue() + dy[i];
                if(valid(nextX, nextY, visited, mat)){
                    mat[nextX][nextY] = mat[currentPos.getKey()][currentPos.getValue()] + 1;
                    queue.offer(new Pair<>(nextX, nextY));
                    visited[nextX][nextY] = true;
                }
            }
        }

        return mat;
    }

    boolean valid(int nextX, int nextY, boolean[][] visited, int[][] mat){
        return (
                0 <= nextX && nextX < mat.length && 0 <= nextY && nextY < mat[0].length &&
                        !visited[nextX][nextY] && mat[nextX][nextY] != 0
                );
    }
}
posted @ 2023-01-15 15:23  Frodo1124  阅读(19)  评论(0编辑  收藏  举报