题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

m, n = map(int, input().split())
maze = []
for i in range(m):
    maze.append(list(map(int, input().split())))

# dirs = [
#     lambda x,y: (x+1, y),
#     lambda x,y: (x-1, y),
#     lambda x,y: (x, y+1),
#     lambda x,y: (x, y-1)
# ]
# 上述dir方法等同于:
def ne_point(x,y):  # 用来表示该节点的邻节点
    return [(x, y+1),(x+1, y),(x, y-1),(x-1, y)]


def dayin(path):
    cur_node = path[-1]
    realpath = []
    while cur_node[2] != -1:
        realpath.append(cur_node)
        cur_node = path[cur_node[2]]
    realpath.append(path[0])
    realpath.reverse()
# print(realpath)
    for node in realpath:
        print('('+str(node[0])+','+str(node[1])+')')

def maze_path(x1, y1, x2, y2): #开始坐标和结束坐标
    queue = []   # 创建队列
    queue.append((x1, y1, -1))
    path = []
    #  第三个数表示当前节点的上一个节点在path中的索引,为了区分与新加入的节点,初将其始化为-1
    path.append((x1,y1, -1))
    maze[x1][y1] = 2  # 将初始节点标记为已走过,注意,DFS不能将初始节点标记为已走过
    while queue:
        current_point = queue.pop(0)  # 出队

        for next_point in ne_point(current_point[0], current_point[1]):
            if 0 <= next_point[0] <= m-1 and 0 <= next_point[1] <= n-1:
                if maze[next_point[0]][next_point[1]] == 0:# 找到了可用的邻节点
                    # 将邻节点以及上一个节点在path中的索引加入队列
                    queue.append((next_point[0], next_point[1], path.index(current_point)))
                    maze[next_point[0]][next_point[1]] = 2 # 将该邻节点标记为已遍历
                    # 下行代码前两位表示邻节点坐标,第三个元素表示邻节点的上一个节点元素在path中的索引
                    path.append((next_point[0], next_point[1], path.index(current_point)))
                    # 判断是否找到了目标节点,找到则结束程序(bfs一定是最短路径)
                    if next_point[0] == x2 and next_point[1] == y2:
                        return dayin(path)
    else:
        print('未找到目标节点,死胡同')
        return
    
maze_path(0, 0, m-1, n-1)

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务