Leetcode 286. Walls and Gates(python+cpp)

这篇博客介绍了LeetCode第286题《Walls and Gates》的解题思路。题目要求在含有障碍(-1)和空房间(INF)的二维网格中,填充每个空房间到最近门的距离。首先,博主尝试了暴力解法,使用DFS,但由于可能存在多个路径,DFS效率较低,导致超时。接着,博主提出了逆向寻找的解法,从门出发,通过BFS更新每个位置的距离,并在过程中比较并更新最小距离。这种解法的时间复杂度为O(mn),空间复杂度也为O(mn)。最后,提供了C++实现的代码。
摘要由CSDN通过智能技术生成

题目

You are given a m x n 2D grid initialized with these three possible values.

  • -1 - A wall or an obstacle.
  • 0 - A gate.
  • INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
    Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.
    在这里插入图片描述

解法1:brutal force(TLE)

从每个位置出发,跟number of islands的方法一样进行BFS寻找最近的gate。但是这个题目跟number of islands不一样的地方在于,可能存在多个可能的路径,而我们要取其中最短的那个。所以对于DFS来说,算法会遍历所有的路径,在这个过程中需要keep track of最短的那个路劲。但是如果用BFS的话,我们并不需要把所有路径找一遍然后选最小的,对于这个问题,lc官方是这么描述的:Since BFS guarantees that we search all rooms of distance d before searching rooms of distance d + 1, the distance to an empty room must be the shortest. 所以这道题目BFS应该会比DFS要快,这边只展示BFS的方法,但这样brutal force的方法依然是超时的

class Solution:
    def wallsAndGates(self, rooms: List[List[int]]) -> None:
        """
        Do not return anything, modify rooms in-place instead.
        """
        def helper(i,j):
            distance = [[0]*len(rooms[0]) for _ in range(len(rooms))]
            q = collections.deque()
            q.append((i,j))
            dirs = [[0,1],[0,-1],[-1,0],[1,0]]
            while q:
                pos = q.popleft()
                for d in dirs:
                    x = d
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值