如何寻找迷宫出口?

问题描述:
A maze is a rectangular grid of cells with walls between some of adjacent cells.
You would like to check whether there is a path from a given cell to a given
exit from a maze where an exit is also a cell that lies on the border of the maze
(in the example shown to the right there are two exits: one on the left border
and one on the right border). For this, you represent the maze as an undirected
graph: vertices of the graph are cells of the maze, two vertices are connected by
an undirected edge if they are adjacent and there is no wall between them. Then,
to check whether there is a path between two given cells in the maze, it suffices to
check that there is a path between the corresponding two vertices in the graph.
Problem Description

任务:Given an undirected graph and two distinct vertices 𝑢 and 𝑣, check if there is a path between 𝑢 and 𝑣.

输入:An undirected graph with 𝑛 vertices and 𝑚 edges. The next line contains two vertices 𝑢
and 𝑣 of the graph.

限制:2 ≤ 𝑛 ≤ 10^3; 1 ≤ 𝑚 ≤ 10^3; 1 ≤ 𝑢, 𝑣 ≤ 𝑛; 𝑢!= 𝑣.

输出:Output 1 if there is a path between 𝑢 and 𝑣 and 0 otherwise.

环境:python 3.10

visit = []
def reach(adj, x, y):
    #algorithm to decide if y is reachable to x
    for i in adj[x]:
        if i not in visit:
            visit.append(i)
            reach(adj, i, y)
    #1 is for reachability,0 is for not reachability
    if y in visit:
        return 1
    else:
        return 0

if __name__ == '__main__':
    #initialization
    n, m = map(int, input().split())
    lines = [[] for _ in range(m)]
    for i in range(m):
        lines[i] = list(map(int, input().strip().split()))
    a, b = map(int, input().split())
    #build a list to store reachable vertexs of each vertex
    adj = [[] for _ in range(n)]
    for line in lines:
        l1 = line[0]
        l2 = line[1]
        adj[l1-1].append(l2-1)
        adj[l2-1].append(l1-1)
    print(reach(adj, a-1, b-1))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值