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?