简体   繁体   中英

Return all possible paths, having built a predecessor dictionary in Python

If I have a predecessor dictionary for a single direction graph generated, such as:

{'A': [], 'B': ['A'], 'C': ['B'], 'D': ['B', 'C'], 'E': ['D']}

How could I:

1) find all possible paths from point A to E and print them?

Thank you!

Code pasted below:

Code clarification:

G is a tuple of tuples, the inner tuples being pairs of vertices that are connected in one way: ((begin, end) (begin,end))

s is start node

e is end node

def dfs_stack(G,s,e):
    stack = [s] 
    vertices = set([j for t in G for j in t]) 
    visited = dict([(v, False) for v in vertices])
    predecessor = dict([(v, []) for v in vertices])
    while stack:
        u = stack.pop()
        if visited[u] == False:
            visited[u] = True
            for w in get_neighbors(u, G): 
                if visited[w] == False:
                    predecessor[w].append(u)
                    stack.append(w)
                elif (visited[w] == True and w != e):
                    return 'CYCLICAL GRAPH'
    return predecessor_to_path(predecessor,s, e)

def predecessor_to_path(pdict, s, end, l=[]):
    l.append(end)
    if end == s:
        return l
    else:
        for p in pdict[end]:
           return predecessor_to_path(pdict, s, p, l)

Currently, this only returns the shortest path. Any ideas on how predecessor_to_path could be modified to return ALL paths?

This is all done with classic graph algorithms, like depth-first search.

Here is a starting point:

http://en.wikipedia.org/wiki/Spanning_tree#Algorithms

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM