问题
I have an undirected graph and i want to list all possible paths from a starting node. Each connection between 2 nodes is unique in a listed path is unique, for example give this graph representation:
{A: [B, C, D],
B: [A, C, D],
C: [A, B, D],
D: [A, B, C]}
some listed path starting from A
A, B, C, D, A, C in this path we have a connection between
A and B but we can't have a connection between B and A
I can't accomplish it using the existing algorithm that i know like DFS . Any help will be very appreciated .
回答1:
The simplest way would be to recursively try each neighbor and combine all the results.
This assumes there are no loops - if you allow loops (as in your example) there will be infinitely-many paths. In this case, you can make a path-generator by limiting the path-length to check for, then looping over all possible path-lengths.
回答2:
A probably most intuitive way would be to, as previously suggested, iterate over all neighbours of each potential starting point until all paths are exhausted.
However, the risk with this method is that it tends to loop forever if the graph has cycles. This can be mitigated by using a list of visited vertices (or, probably preferable in your case, visited edges)
In pseudocode, that might give something like this:
paths = []
for node in graph
visited = []
path = [node]
add node and path to stack-or-queue
while node on stack-or-queue
pop node and path
for edges of node
if edge is not visited
add edge to visited
add neighbour to path
add neighbour and path to stack-or-queue
add path to paths
It produces an algorithm of relatively high complexity, so be sure to test it well to avoid crap.
Writing it recursively might be easier, although it removes the possibility of easily changing between DFS and BFS.
来源:https://stackoverflow.com/questions/52298423/find-all-paths-on-undirected-graph