I recently discovered the Hamiltonian Path/Circuit in CodeBullet's Snake A.I. video and decided to give it a go myself. I wrote a basic Depth First Search algorithm to visit all the nodes in a graph and store the path when the circuit is complete.
Here is the pseudocode for the algorithm:
# 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, start, curPath.copy(), depth + 1)
This implementation works in theory since it does provide me a solution for a 6x6 grid and below but the problem is, it is extremely slow. It could not even provide a solution for an 8x8 grid when in the video, it was mentioned that it was a very fast algorithm which also showed since he had computed Hamiltonian circuits for 50x50 grids.
I would really like to know how I can speed this up since I am sure my beginner skills are not enough to point out some glaring flaws which you could probably see pretty easily. Any help is appreciated.