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

时间:2019-04-01 06:32:19

标签: python-3.x algorithm graph breadth-first-search

我正在上一幅图算法课程,我被困在寻找两个顶点之间的最短路径的问题上。

问题陈述:给出具有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 shorter path
                q.insert(0, i)
                vis[i] = vis[u] + 1

    return vis[end]

if True:
    n, m = map(int, input().split()) # n : vertices, m : edges
    arr = {} # stores edges

    for i in range(m): # accepts edges as inputs
        a, b = map(int, input().split()) # (a,b) >(0,0)

        if a-1 in arr.keys():
            arr[a-1].append(b-1)
        else:
            arr[a-1] = [b-1]

        if b-1 in arr.keys():
            arr[b-1].append(a-1)
        else:
            arr[b-1] = [a-1]

    if m > 0:
        start, end = map(int, input().split()) # start : source node, end = dest node 
        vis = [-1 for i in range(n)] # will store shortest path for each node
        print(explore(arr, start-1, end-1, vis))
    else:
        print(-1)

enter image description here

1 个答案:

答案 0 :(得分:2)

由于索引问题,您的代码有问题。您在此处使用从1开始的索引:q = [start],但后来使用从0开始的索引:for i in arr[u](注意,没有-1),依此类推。我严格建议在任何地方都使用0中的索引-它绝对更具可读性,并且有助于避免索引可能出现的错误。另外,如果您将新项目添加到elif的末尾(出于某种原因,您将其插入q的开头),则实际上并不需要q。更正的代码(警告-输入参数的索引从0开始到处都是!):

def explore(arr, start, end, vis):
    vis[start] = 0
    q = [start] # queue for storing the node for exploring

    while len(q): # 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.append(i)
                vis[i] = vis[u] + 1

    return vis[end]