BFS准备兔子逃生

问题描述

提示

您有空间站的各个部分的地图,每个地图的起点是监狱出口,终点是逃生舱门。该地图用0和1的矩阵表示,其中0是可通过的空间,而1s是不可通过的墙。从监狱出来的门在左上角(0,0),进入逃生舱的门在右下角(w-1,h-1)。

编写一个函数答案(图),该函数生成从监狱门到逃生舱的最短路径的长度,在此范围内,您可以移走一堵墙作为改建计划的一部分。路径长度是您经过的节点总数,同时计算入口和出口节点。起始位置和结束位置始终是可通过的(0)。尽管您可能需要也可能不需要删除墙,但地图始终可以解决。地图的高度和宽度可以为2到20。只能在基本方向上移动。不允许对角移动。

测试用例

maze = [
    [0,1,0],[0,[1,1],0]
]
#15

maze = [
    [0,0]
]
#21

maze = [
    [0,0]
]
#39

maze = [
    [0,0]
]
#10

我的代码

from collections import deque


def solution(map):
    H = len(map)
    W = len(map[0])
    start = ((0,0),False)

    track = {
        (0,0): (-1,-1)
    }
    to_explore = deque([start])
    visited = set()
    w,h = 0,0
    while not (w == W-1 and h == H-1):
        current = to_explore.popleft()
        pos,opened = current
        neighbours = get_neighbours(pos)
        zeroes,ones = check_neighbours(neighbours,map,(W,H))
        for node in zeroes:
            if not node in track and node not in visited:
                form_vertex = (node,opened)
                to_explore.append(form_vertex)
                track[node] = pos
        for node in ones:
            if not node in track and node not in visited and not opened:
                form_vertex = (node,True)
                to_explore.append(form_vertex)
                track[node] = pos
        w,h = pos
        visited.add(pos)

    path = []
    current = (W - 1,H - 1)
    while current != (-1,-1):
        path.append(current)
        current = track[current]
    return len(path)


def get_neighbours(pos):
    w,h = pos
    return [(w+1,h),(w-1,(w,h+1),h-1)]


def check_neighbours(neighbours,grid,edge):
    zeroes = []
    ones = []
    W,H = edge
    for neighbour in neighbours:
        w,h = neighbour
        if 0 <= w < W and 0 <= h < H:
            value = grid[h][w]
            if value == 0:
                zeroes.append(neighbour)
            else:
                ones.append(neighbour)

    return zeroes,ones

问题

据我所知,该代码有效。它通过了我抛出的所有测试用例。但是,它未能通过Google的两个隐藏测试用例。谁能找出问题所在,并告诉我我所缺少的,因为我已经用尽了自己的想法,而我似乎并没有发现什么地方出了问题。
!!即使您找不到解决方案,也可以通过失败的测试用例

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)