I'm trying to port the following example python code to Java:
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
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, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
The problem being, the base case to stop recursing:
if start == end:
return [path]
It doesn't support my requirement of allowing both A and N to be the same node.
For example:
If I have the following digraph :
A -> [B, C],
B -> [C, E],
C -> [D, A]
And I want all paths between A and A, I should have the result:
A -> B -> C -> A
The above python code will just give me:
A
A path from A to A must go through a neighbor of A. Thus, one way to implement this is to enumerate all of the outward neighbors:
[[["A"]+y for y in find_all_paths(G,x,"A")] for x in graph["A"]]
For your graph, the result should be
[[['A', 'B', 'C', 'A']], [['A', 'C', 'A']]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.