-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_all_paths.py
47 lines (42 loc) · 1.62 KB
/
find_all_paths.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def main():
NeighborNodes = dict()
NeighborNodes['A'] = ['B', 'D', 'H']
NeighborNodes['B'] = ['A', 'D','C']
NeighborNodes['C'] = ['B', 'D','F']
NeighborNodes['D'] = ['A', 'B', 'C', 'E']
NeighborNodes['E'] = ['D', 'F','H']
NeighborNodes['F'] = ['C', 'E', 'G']
NeighborNodes['G'] = ['F', 'H']
NeighborNodes['H'] = ['A', 'E', 'G']
paths = getAllSimplePaths('A', 'H', NeighborNodes)
for path in paths:
print(path)
def getAllSimplePaths(originNode, targetNode, NeighborNodes):
return getAllPaths(targetNode,
[originNode],
set(originNode),
NeighborNodes,
list())
def getAllPaths(targetNode,
currentPath,
usedNodes,
NeighborNodes,
answerPaths):
lastNode = currentPath[-1]
if lastNode == targetNode:
answerPaths.append(list(currentPath))
else:
for neighbor in NeighborNodes[lastNode]:
if neighbor not in usedNodes:
currentPath.append(neighbor)
usedNodes.add(neighbor)
getAllPaths(targetNode,
currentPath,
usedNodes,
NeighborNodes,
answerPaths)
usedNodes.remove(neighbor)
currentPath.pop()
return answerPaths
if __name__ == '__main__':
main()