solutions=[] #appends all paths from a to b which are shorter than |g.edges()| to solutions
def path(g,a,b,c=0,li=[]): #and returns if there is a solution
if a==b:
solutions.append(li)
return (a==b or true in [path(g,x,b,c+1,li+[x]) for x in g.neighbors(a)] if c<=len(g.edges()) else false)
a=4; b=7
G=Graph({1:[2,7],5:[6],3:[1,2,5,6,4]})
show(plot(G))
if path(G,a,b):
M=[len(x) for x in solutions];
print "shortest path from",a,"to",b,[a]+solutions[M.index(min(M))]
else:
print "there is no path from",a,"to",b
|
|
shortest path from 4 to 7 [4, 3, 1, 7]
shortest path from 4 to 7 [4, 3, 1, 7]
|