Nelogeek

Hamilton's cycle

Oct 28th, 2021
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.69 KB | None | 0 0
  1. def hamilton(G, size, pt, path=[]):
  2.     print('hamilton called with pt={}, path={}'.format(pt, path))
  3.     if pt not in set(path):
  4.         path.append(pt)
  5.         if len(path)==size:
  6.             return path
  7.         for pt_next in G.get(pt, []):
  8.             res_path = [i for i in path]
  9.             candidate = hamilton(G, size, pt_next, res_path)
  10.             if candidate is not None:  # skip loop or dead end
  11.                 return candidate
  12.         print('path {} is a dead end'.format(path))
  13.     else:
  14.         print('pt {} already in path {}'.format(pt, path))
  15.     # loop or dead end, None is implicitly returned
  16.  
  17.  
  18. G = {1:[2,3,4], 2:[1,3,4], 3:[1,2,4], 4:[1,2,3]}
  19. hamilton(G,4,1,[])
  20.  
Advertisement
Add Comment
Please, Sign In to add comment