Leetcode286墙与门

本文介绍了解决LeetCode上编号为286的题目房间与门的算法实现。该算法使用广度优先搜索策略,从所有门的位置开始,计算每个空房间到最近门的距离,并更新房间矩阵中的距离值。文章详细解释了算法流程,包括初始化搜索队列,进行广度优先搜索,更新距离值等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

286墙与门

#286墙与门
class Solution:
    def wallsAndGates(self, rooms):
        EMPTYROOM = 2**31 - 1
        door = 0
        neighbors = [[-1,0], [1,0], [0,-1], [0,1]]
        if not rooms:
            return
        row = len(rooms)
        col = len(rooms[0])
        searchlist = deque()
        for i in range(row):
            for j in range(col):
                if rooms[i][j] == door:
                    searchlist.append(([i,j], 0))

        while searchlist:
            [n_row, n_col], distance = searchlist.popleft()
            for d_row, d_col in neighbors:
                neighbor_row = d_row + n_row
                neighbor_col = d_col + n_col
                if 0 <= neighbor_row < row and 0<=neighbor_col < col \
                    and rooms[neighbor_row][neighbor_col] == EMPTYROOM:
                    rooms[neighbor_row][neighbor_col] = distance + 1
                    searchlist.append(([neighbor_row,neighbor_col], distance + 1))
        return print(rooms)

data = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
data1 = []
data2 = [[-1]]
data3 = [[2147483647]]
data4 = [[2147483647,0,2147483647,2147483647,0,2147483647,-1,2147483647]]
solution = Solution()
solution.wallsAndGates(data)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值