问题
Possible Duplicate:
Find the paths between two given nodes?
Given a directed graph, how to find ALL the possible paths between two nodes and return those paths.
If not in Java, please recommend me with the algorithm for it. I searched and what I found is using BFS or DFS, but I'm not able to see which is better in my case. And how to keep track of all paths not only the shortest one.
For example, given the following graph:
1 -> 2
1 -> 3
2 -> 3
3 -> 4
For paths between nodes 1 and 4, the output should be:
First Path: 1 -> 2 -> 3 -> 4
Second Path: 1 -> 3 -> 4
回答1:
To me, backward traversal is much easier. Algorithm steps as below:
- Start from destination (i.e. 4 in your example) as starting point.
- Collect all nodes which has second element as destination e.g. (3,4).
- Assume starting point (
3
in first iteration) as new destination and repeat steps1
&2
until there is no matching node available. Good scenario of recursion. You will get your collection as: [(1,2), (2,3), (3,4)], [(1,3), (3,4)] - Check the collection created above and if the reverse destination is equal to your source then keep it otherwise discard (in your case, there is nothing to discard). YOU ARE DONE.
来源:https://stackoverflow.com/questions/13852480/find-all-possible-paths-between-two-nodes-in-a-directed-labeled-graph