Find ALL possible paths between two nodes in a directed labeled graph [duplicate]

China☆狼群 提交于 2019-12-12 04:33:31

问题


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:

  1. Start from destination (i.e. 4 in your example) as starting point.
  2. Collect all nodes which has second element as destination e.g. (3,4).
  3. Assume starting point (3 in first iteration) as new destination and repeat steps 1 & 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)]
  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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!