【算法日记】路径算法
此算法适合带有负边权的和无负边权的有向图。算法会计算出所有可能的路径和每个路径的长度
1 ways={ 2 "A":{ 3 "B":5, 4 "C":2 5 }, 6 "B":{ 7 "C":4 8 }, 9 "C":{ 10 "D":5, 11 }, 12 "D":None 13 } 14 15 def findWay(ways,start,end): 16 17 wayList={} 18 19 def search(string): 20 node=string[-1] 21 if ways[node]: 22 nodeList=ways[node].keys() 23 for item in nodeList: 24 if item==end: 25 wayList[string+item]=getValue(string+item) 26 else: 27 newPath=string+item 28 search(newPath) 29 30 def getValue(string): 31 l=len(string) 32 v=0 33 for i in range(l-1): 34 key1=string[i] 35 key2=string[i+1] 36 v+=int(ways[key1][key2]) 37 return v 38 39 for key in ways[start]: 40 new=start+key 41 search(new) 42 print wayList 43 44 findWay(ways,"A","D")
输出:
负边权图:
1 ways={ 2 "A":{ 3 "B":5, 4 "C":2 5 }, 6 "B":{ 7 "C":-4 8 }, 9 "C":{ 10 "D":5, 11 }, 12 "D":None 13 } 14 15 def findWay(ways,start,end): 16 17 wayList={} 18 19 def search(string): 20 node=string[-1] 21 if ways[node]: 22 nodeList=ways[node].keys() 23 for item in nodeList: 24 if item==end: 25 wayList[string+item]=getValue(string+item) 26 else: 27 newPath=string+item 28 search(newPath) 29 30 def getValue(string): 31 l=len(string) 32 v=0 33 for i in range(l-1): 34 key1=string[i] 35 key2=string[i+1] 36 v+=int(ways[key1][key2]) 37 return v 38 39 for key in ways[start]: 40 new=start+key 41 search(new) 42 print wayList 43 44 findWay(ways,"A","D")
输出: