简体   繁体   中英

finding all paths from given graph python

I need to find all paths from a given graph. I can do that for now however my recursive code is not efficient also my graphs are very complicated. Hence I need a better algorithm. Here is my code so far,

def findLeaves(gdict):
    # takes graph and find its leaf nodes
    leaves = []
    for endNode in gdict.iterkeys():
        if not gdict[endNode]:
            leaves.append(endNode)
    return leaves

graphPaths = {}    
def findPaths(gname, gdict, leave, path):
    # finds all noncycle paths
    if not gdict:
        return []
    temp = [node for node in gdict.iterkeys() if leave in gdict[node].keys() and node not in path] 
    if temp:
        for node in temp:
            findPaths(gname, gdict, node, [node] + path) 
    else:
        graphPaths[gname].append(path)   




    # main
    leaves = findLeaves(graph['graph'])
    graphPaths['name'] = []

    seenNodes = []
    for leave in leaves:
        findPaths(graph['name'], graph['graph'], leave, [leave])

There is only one starting node, which makes things easier for recursive function. Every leaf needs to arrive there if a leaf is followed in reverse order. Starting node is the one which does not have an incoming edge.

I have lots of graphs so I keep them in dictionary. Keys are the names of graphs. Here is an example for my data:

graph['graph']: {
0: {1: {}}, 
1: {2: {}, 3: {}}, 
2: {3: {}}, 
3: {4: {}}, 
4: {5: {}}, 
5: {6: {}}, 
6: {7: {}}, 
7: {6: {}, 5: {}}
}

graph['name'] = nameofthegraph

These structure is taken from pygraphviz , it simply shows the outgoing edges from any nodes. Keys are the nodes and values are outgoing edges to the nodes. However when I have very complicated graphs as below, this code could not find all paths.

在此处输入图片说明

Is there any better algorithm that you can suggest? Or is there any way to optimize my algorithm for complicated graphs?

Why did you need to find all paths from a given graph ? Which context ? I ask you this question because as Graph Theory is something very popular in Computing today, there is probably a algorithm which fit exactly your needs...

For example, if finally you need to compare all paths to found the best one, you probably may be interested in "Shortest path problem" and read: Find all paths between two graph nodes & https://en.wikipedia.org/wiki/Shortest_path_problem

About the "optimization" subject, python allow you to use list comprehension, multithreaded and/or subprocess based code.

You may also try to use a "native graph database" (like neo4js), to store your node, and then use some built in methods like: http://neo4j.com/docs/stable/cypherdoc-finding-paths.html to do the job.

Best regards

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