小编Ar7*_*Ar7的帖子

我应该在哪里修改广度优先搜索算法以找到2个节点之间的最短路径?

我正在学习一个图算法课程,我一直陷入寻找两个顶点之间最短路径的问题。

问题陈述:给定一个具有n个顶点和m个边以及两个顶点u和v的无向图,计算u和v之间最短路径的长度。输出从u到v的路径中最小边数,或者如果没有路径,则为?1。

我的代码正在通过一些测试用例,但其中很少有失败,而且我真的看不到哪里出了问题,因此,任何形式的洞察都将真正有用。

def explore(arr, start, end, vis):

    vis[start] = 0; q = [start] # queue for storing the node for exploring

    while len(q) != 0:  # iterates till queue isn't empty
        u = q.pop()
        for i in arr[u]: # checks for all nodes connected to uth node
            if vis[i] == -1: # if the node is unvisited
                q.insert(0, i)
                vis[i] = vis[u] + 1
            elif vis[i] > vis[u] + 1: # if the visited node has …
Run Code Online (Sandbox Code Playgroud)

algorithm graph breadth-first-search python-3.x

7
推荐指数
1
解决办法
751
查看次数