基于Python实现迪杰斯特拉和弗洛伊德算法

时间:2021-05-22

图搜索之基于Python的迪杰斯特拉算法和弗洛伊德算法,供大家参考,具体内容如下

Djstela算法

#encoding=UTF-8MAX=9'''Created on 2016年9月28日@author: sx'''b=999G=[[0,1,5,b,b,b,b,b,b],\ [1,0,3,7,5,b,b,b,b],\ [5,3,0,b,1,7,b,b,b],\ [b,7,b,0,2,b,3,b,b],\ [b,5,1,2,0,3,6,9,b],\ [b,b,7,b,3,0,b,5,b],\ [b,b,b,3,6,b,0,2,7],\ [b,b,b,b,9,5,2,0,4],\ [b,b,b,b,b,b,7,4,0]]P=[]D=[]def Djstela(G,P,D): final=[] for i in range(0,len(G)): final.append(0) D.append(G[0][i]) P.append(0) D[0]=0 final[0]=1 k=0 for v in range(1,len(G)): min=999 for w in range(0,len(G)): if final[w]==0 and D[w]<min: k=w min=D[w] final[k]=1 for t in range(0,len(G)): if min+G[k][t]<D[t]: D[t]=min+G[k][t] P[t]=k print("\n最短路径\n",D,"\n","\n前一个选择\n",P)def search(x): print("选择的终点",x,"最短路径",D[x]) print("邻接矩阵\n")for i in range(0,9): print(G[i])Djstela(G, P, D)q=input("\n请输入终点")search(int(q))

FLOYD算法

#encoding=UTF-8'''Created on 2016年9月28日@author: sx'''t=0b=999G=[[0,1,5,b,b,b,b,b,b],\ [1,0,3,7,5,b,b,b,b],\ [5,3,0,b,1,7,b,b,b],\ [b,7,b,0,2,b,3,b,b],\ [b,5,1,2,0,3,6,9,b],\ [b,b,7,b,3,0,b,5,b],\ [b,b,b,3,6,b,0,2,7],\ [b,b,b,b,9,5,2,0,4],\ [b,b,b,b,b,b,7,4,0]]P=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],\ [0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],\ [0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]D=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],\ [0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],\ [0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]def Floyd(G,P,D): t=0 for u in range(0,len(G)): for s in range(0,len(G)): D[u][s]=G[u][s] P[u][s]=s for k in range(0,len(G)): for v in range(0,len(G)): for w in range(0,len(G)): if D[v][w]>D[v][k]+D[k][w]: t=t+1 D[v][w]=D[v][k]+D[k][w] P[v][w]=P[v][k] Floyd(G, P, D)def search(s,u): lenth=D[s][u] print("路径长度为",lenth) f=P[s][u] foot=[s,f] if f==u: print("无需规划,0步") while f!=u: f=P[f][u] foot.append(f) for i in range(0,len(foot)): if i==0: print("起 点____",foot[i]) elif i==len(foot)-1: print("终 点____",foot[i],"步长___",G[foot[i-1]][foot[i]]) else: print("第",i,"点____",foot[i],"步长___",G[foot[i-1]][foot[i]])print("邻接矩阵")for i in range(0,9): print(G[i])s=input("请输入起点0-8\n")u=input("请输入终点0-8\n")Floyd(G, P, D)search(int(s),int(u))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章