【问题标题】:Recursive DFS shortest path implementation not working as expected递归 DFS 最短路径实现未按预期工作
【发布时间】:2015-09-17 14:13:23
【问题描述】:

对于大学作业,我们必须为加权图实现递归朴素最短路径算法。它应该检查所有路线,从中我们可以找到最短的路线。

我们已经在 Python 脚本上工作了很长时间,但我们无法让它正常工作。这就是我们现在所拥有的:

import numpy as np
global paths
paths = []

class Path:
        def __init__(self):
            self.NodeArray = [];
            self.Weight = 0;


def vindpaden(start,end,pad):
    pad.NodeArray.append(start)
    print "path so far: " + str(pad.NodeArray)
    global paths
    print "Start:" + str(start) + ", " + "end: " + str(end)
    if start == end:
        print "returning"
        paths.append(pad)
    else:
        for j in range(len(graph)):
            if (j not in pad.NodeArray) and graph[start][j] != -1:
                newpaths = vindpaden(j,end,pad)

graph = np.loadtxt("input2.txt")
graph = graph.astype(int)

start = 0
end = 1

path = Path()
vindpaden(start,end,path)

print "###### results:"
for p in paths:
    print "length: " + str(p.Weight) + ", path: " + str(p.NodeArray)

我们使用邻接矩阵作为输入。对于测试,我们使用简单的测试图:

使用以下邻接矩阵(其中-1表示无连接):

-1 -1  1 -1
 3 -3 -1 -1
 2  2 -1  1
-1  2 -1 -1

这会产生以下输出:

path so far: [0]
Start:0, end: 1
path so far: [0, 2]
Start:2, end: 1
path so far: [0, 2, 1]
Start:1, end: 1
returning
path so far: [0, 2, 1, 3]
Start:3, end: 1
######
length: 0, path: [0, 2, 1, 3]

所以你可以看到它通过 2 找到了从点 0 到点 1 的路径,之后它应该将路径 [0,2,1] 添加到数组路径并继续寻找从点 2 开始的路径。相反,它返回(不正确的)路径 [0,2,1,3]。最后,数组paths中唯一的路径是[0,2,1,3],也很奇怪。

这是我们期望的输出:

path so far: [0]
Start:0, end: 1
path so far: [0, 2]
Start:2, end: 1
path so far: [0, 2, 1]
Start:1, end: 1
returning
path so far: [0, 2, 3]
Start:3, end: 1
path so far: [0 ,2, 3, 1]
Start:1, end: 1
returning
######
length: 0, path: [0, 2, 1]
length: 0, path: [0, 2, 3, 1]

请注意,我们目前没有使用 weight 属性。任何帮助将不胜感激!

吉姆

【问题讨论】:

    标签: python recursion graph depth-first-search


    【解决方案1】:

    看起来您的问题是您只创建了一个 Path() 实例,这会导致该实例的 NodeArray 损坏。我认为发生的情况如下:

    • 您会发现NodeArray 包含[0, 2, 1]
    • 该函数检测到它已到达目标,因此返回最近的节点以检查其余的潜在路径。
    • 从节点2开始,1之后的下一个节点是3,所以3被添加到NodeArray列表中。因为列表还没有被清空,所以新节点(3)只是添加到最后,导致[0, 2, 1, 3]。
    • 现在,因为 1 已经在您当前的 NodeArray 中,所以 if 语句 if (j not in pad.NodeArray) and graph[start][j] != -1: 失败并且函数停止。

    我认为你需要做的是每次调用vindpaden()时创建一个新的Path(),并将当前PathNodeArray复制到新的Path中。

    【讨论】:

    • 我发现了问题,确实和你说的一模一样。 :) 我通过传递 deepcopy(pad) 而不是 pad 来解决它。我原以为 Python 会按值传递,但在阅读之后,似乎 Python 使用它自己的技巧来传递变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多