【重点】【BFS】542.01矩阵

题目

法1:经典BFS

下图中就展示了我们方法:

java 复制代码
class Solution {
    public int[][] updateMatrix(int[][] mat) {
        int m = mat.length, n = mat[0].length;
        int[][] dist = new int[m][n];
        boolean[][] used = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (mat[i][j] == 0) {
                    queue.offer(new int[]{i, j});
                    used[i][j] = true;
                }
            }
        }
        int[] xMove = new int[]{-1, 1, 0, 0};
        int[] yMove = new int[]{0, 0, -1, 1};
        while (!queue.isEmpty()) {
            int[] curLoc = queue.poll();
            int curX = curLoc[0], curY = curLoc[1];
            for (int i = 0; i < 4; ++i) {
                int xNew = curX + xMove[i];
                int yNew = curY + yMove[i];
                if (xNew >= 0 && xNew < m && yNew >= 0 && yNew < n && !used[xNew][yNew]) {
                    queue.offer(new int[]{xNew, yNew});
                    dist[xNew][yNew] = dist[curX][curY] + 1;
                    used[xNew][yNew] = true;
                }
            }
        }

        return dist;
    }
}
相关推荐
小欣加油5 天前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
小欣加油5 天前
leetcode542 01矩阵
数据结构·c++·算法·leetcode·矩阵·bfs
进击的荆棘11 天前
优选算法——队列+宽搜
数据结构·c++·算法·leetcode·bfs·队列
Misnearch25 天前
1345. 跳跃游戏 IV
java·leetcode·bfs
YL200404261 个月前
041二叉树的层序遍历
数据结构·leetcode·bfs
浅念-1 个月前
LeetCode最短路必看:BFS算法原理+经典题解
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
浅念-1 个月前
刷穿LeetCode:BFS 解决 Flood Fill 算法
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
hnjzsyjyj1 个月前
洛谷 P1443:马的遍历 ← BFS
数据结构·bfs
hnjzsyjyj1 个月前
洛谷 P1746:离开中山路 ← BFS
bfs
星马梦缘1 个月前
算法设计与分析 作业二 答案与解析
算法·图论·dfs·bfs·floyd-warshall·bellman_ford·多源最短路