一种有效的哈密顿回路算法

问题描述

我最近在 CodeBullet 的 Snake A.I. 中发现了哈密顿路径/电路。视频并决定自己试一试。我写了一个基本的深度优先搜索算法来访问图中的所有节点并在电路完成时存储路径。

这是算法的伪代码

# Global list to store the Hamilton Circuit
hamiltonPath = []

# Recursive DFS Function
def dfs(node,start,currentPath = [],depth = 1):
    # Return if the circuit is already discovered
    if hamiltonPath != []: return

    # Add current node to current path
    curPath.append(node)

    # Explore neighbors of the current node
    for neighbor in node.neighbors:
        # Check if the neighbor completes the circuit
        if neighbor == start and depth == totalNodes:
            curPath.append(neighbor)
            hamiltonPath = curPath.copy()
            return

        # Otherwise if neighbor is unvisited continue DFS search
        if neighbor not in curPath:
            dfs(neighbor,curPath.copy(),depth + 1)

这个实现在理论上是有效的,因为它确实为我提供了一个 6x6 网格及以下的解决方案,但问题是,它非常慢。它甚至无法为 8x8 网格提供解决方案,在视频中提到这是一种非常快的算法,因为他已经为 50x50 网格计算了哈密顿电路。

我真的很想知道如何加快速度,因为我确信我的初学者技能不足以指出一些您可能很容易看到的明显缺陷。任何帮助表示赞赏。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)