这篇文章主要为大家展示了基于Python如何实现Djstela和FLOYD算法,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。
Djstela算法
#encoding=UTF-8 MAX=9 ''' Created on 2016年9月28日 @author: sx ''' b=999 G=[[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=0 b=999 G=[[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))
以上就是关于基于Python如何实现Djstela和FLOYD算法的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。