使用 Python 的“哈密尔顿”路径

Max*_*Max 3 python recursion backtracking recursive-backtracking

我正在尝试使用 Python 实现遍历所有图顶点的任意路径(不一定是循环)的递归搜索。这是我的代码:

def hamilton(G, size, pt, path=[]):
    if pt not in set(path):
        path.append(pt)
        if len(path)==size:
            return path
        for pt_next in G[pt]:
            res_path = [i for i in path]
            hamilton (G, size, pt_next, res_path)
Run Code Online (Sandbox Code Playgroud)

这里,pt是起点,path是之前遍历过的所有顶点的列表,不包括pt,默认为空。问题是,每当找到这样的路径时,返回语句都会引用过程的某些内部调用,因此程序不会终止或返回该路径。

例如,获取G = {1:[2,3,4], 2:[1,3,4], 3:[1,2,4], 4:[1,2,3]}(即完整的 4 图)并运行hamilton(G,4,1,[])。它返回None,但如果您打印路径而不是将其作为值返回,您会发现它实际上找到了从 1 开始的所有六个路径。

如果我告诉程序将路径与 return 语句一起打印,它最终会打印所有此类路径,因此运行时间比需要的时间长得多。

如何修复代码,以便在找到第一个合适的路径后终止执行?

mkr*_*er1 5

基本错误是,如果递归调用没有导致死胡同,则需要返回结果。

此外,如果该点没有邻居,G[pt]则会引发。这可以通过使用轻松解决。IndexErrorptdict.get

def hamilton(G, size, pt, path=[]):
    print('hamilton called with pt={}, path={}'.format(pt, path))
    if pt not in set(path):
        path.append(pt)
        if len(path)==size:
            return path
        for pt_next in G.get(pt, []):
            res_path = [i for i in path]
            candidate = hamilton(G, size, pt_next, res_path)
            if candidate is not None:  # skip loop or dead end
                return candidate
        print('path {} is a dead end'.format(path))
    else:
        print('pt {} already in path {}'.format(pt, path))
    # loop or dead end, None is implicitly returned
Run Code Online (Sandbox Code Playgroud)

例子

def hamilton(G, size, pt, path=[]):
    print('hamilton called with pt={}, path={}'.format(pt, path))
    if pt not in set(path):
        path.append(pt)
        if len(path)==size:
            return path
        for pt_next in G.get(pt, []):
            res_path = [i for i in path]
            candidate = hamilton(G, size, pt_next, res_path)
            if candidate is not None:  # skip loop or dead end
                return candidate
        print('path {} is a dead end'.format(path))
    else:
        print('pt {} already in path {}'.format(pt, path))
    # loop or dead end, None is implicitly returned
Run Code Online (Sandbox Code Playgroud)
>>> G = {1:[2,3,4], 2:[1,3,4], 3:[1,2,4], 4:[1,2,3]}
>>> hamilton(G, 4, 1)
hamilton called with pt=1, path=[]
hamilton called with pt=2, path=[1]
hamilton called with pt=1, path=[1, 2]
pt 1 already in path [1, 2]
hamilton called with pt=3, path=[1, 2]
hamilton called with pt=1, path=[1, 2, 3]
pt 1 already in path [1, 2, 3]
hamilton called with pt=2, path=[1, 2, 3]
pt 2 already in path [1, 2, 3]
hamilton called with pt=4, path=[1, 2, 3]
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
>>> G = {1:[2], 2:[3,4], 4:[3]}
>>> hamilton(G, 4, 1)
hamilton called with pt=1, path=[]
hamilton called with pt=2, path=[1]
hamilton called with pt=3, path=[1, 2]
path [1, 2, 3] is a dead end
hamilton called with pt=4, path=[1, 2]
hamilton called with pt=3, path=[1, 2, 4]
[1, 2, 4, 3]
Run Code Online (Sandbox Code Playgroud)

请注意,由于“可变默认参数”问题,多次使用该函数可能会导致错误的结果。但这不是这个答案的范围。