【重点】【BFS】542.01矩阵

本文介绍了一个名为Solution的类中的updateMatrix方法,通过广度优先搜索(BFS)计算给定矩阵中每个元素到0的距离,返回更新后的距离矩阵。

题目
非常类似题目:994.腐烂的橘子

法1:经典BFS

在这里插入图片描述
下图中就展示了我们方法:
在这里插入图片描述

Python

class Solution:
    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
        q = collections.deque()
        m, n = len(mat), len(mat[0])
        used = [[False]*n for _ in range(m)]
        dis = [[0]*n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if mat[i][j] == 0:
                    q.append([i, j])
                    used[i][j] = True
        dx = [-1, 1, 0, 0]
        dy = [0, 0, -1, 1]
        while q:
            tmp_size = len(q)
            for _ in range(tmp_size):
                cur_xy = q.popleft()
                for i in range(4):
                    nx = cur_xy[0] + dx[i]
                    ny = cur_xy[1] + dy[i]
                    if (0 <= nx < m 
                        and 0 <= ny < n
                        and not used[nx][ny]):
                        dis[nx][ny] = dis[cur_xy[0]][cur_xy[1]] + 1
                        used[nx][ny] = True
                        q.append([nx, ny])
        
        return dis

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值