# based on this: # https://stackoverflow.com/questions/28518369/build-all-hamiltonian-paths-from-an-edge-list graph = { # node: [list of allowed followers] 1: [10], # Song Name 1 2: [5, 3], # Song Name 2 3: [2, 4, 6, 8], # Song Name 3 4: [1, 3, 8, 9], # Song Name 4 5: [1, 2, 3, 6, 7, 8], # Song Name 5 6: [3, 8, 10, 4, 5, 2], # Song Name 1 7: [1, 3, 4, 5, 8], # Song Name 2 8: [3, 9], # Song Name 3 9: [3, 5], # Song Name 4 10: [2], # Song Name 5 } # allowed starting nodes starts = [1, 2, 3] def find_all_paths(graph, start, totallen, path=[]): path = path + [start] if len(path) == totallen: return [path] if not graph.has_key(start): return [] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, totallen, path) for newpath in newpaths: paths.append(newpath) return paths cycles = [] for start in starts: print "Non-cyclic paths starting with", start paths = find_all_paths(graph, start, len(graph), []) for path in paths: first = path[0] last = path[-1] if first in graph[last]: cycles.append(path) else: print path print "Cycles (duplicated for each start song):" for cycle in cycles: print cycle
Standard input is empty
Non-cyclic paths starting with 1 [1, 10, 2, 5, 7, 3, 6, 4, 8, 9] [1, 10, 2, 5, 7, 4, 3, 6, 8, 9] [1, 10, 2, 5, 7, 4, 8, 9, 3, 6] [1, 10, 2, 5, 7, 4, 9, 3, 6, 8] [1, 10, 2, 5, 7, 8, 3, 6, 4, 9] [1, 10, 2, 3, 6, 4, 9, 5, 7, 8] [1, 10, 2, 3, 6, 5, 7, 4, 8, 9] Non-cyclic paths starting with 2 Non-cyclic paths starting with 3 Cycles (duplicated for each start song): [1, 10, 2, 5, 7, 8, 9, 3, 6, 4] [1, 10, 2, 3, 6, 8, 9, 5, 7, 4] [1, 10, 2, 3, 6, 4, 8, 9, 5, 7] [2, 5, 7, 8, 9, 3, 6, 4, 1, 10] [2, 3, 6, 8, 9, 5, 7, 4, 1, 10] [2, 3, 6, 4, 8, 9, 5, 7, 1, 10] [3, 6, 8, 9, 5, 7, 4, 1, 10, 2] [3, 6, 4, 1, 10, 2, 5, 7, 8, 9] [3, 6, 4, 8, 9, 5, 7, 1, 10, 2]