dijkstra:
#dijkstra演算法只能解決有向無負權圖單源最短路徑
#其基本思想是每次找出距離已經訪問過的集合最短邊連線的點,以該點為基準進行鬆弛
#dijkstra演算法只能解決有向無負權圖單源最短路徑
#其基本思想是每次找出距離已經訪問過的集合最短邊連線的點,以該點為基準進行鬆弛
import time
begin=time.clock()
juzhen=[
[0,4,2,5,999,999,999,999,999,999],
[999,0,999,999,7,5,999,999,999,999],
[999,999,0,999,999,9,999,999,999,999],
[999,999,999,0,2,999,7,999,999,999],
[999,999,999,999,0,999,999,4,999,999],
[999,999,999,999,999,0,999,999,999,6],
[999,999,999,999,999,999,0,999,3,999],
[999,999,999,999,999,999,999,0,999,7],
[999,999,999,999,999,999,999,999,0,8],
[999,999,999,999,999,999,999,999,999,0]
]distance=[0 for i in range(10)]#共有十個頂點,表示每個頂點到源點的距離
used=[0 for i in range(10)]#記錄是否已經求得最短路徑(將所有的初始化為0)
used[0]=1#本身已經求得最短路徑0
for i in range(10): #初始化原始距離
distance[i]=juzhen[0][i]
for i in range(1,10): #每次找乙個距離「源點」最近的點
k=1min=999 #999代表無窮大,用其代表沒路可走
for j in range(10): #每次找到距離以標記集合中的最短的點
if(used[j]==0 and distance[j]bellman-ford演算法:
#ford演算法可以用於解決有向圖無向圖以及負邊權圖
#其基本思想是首先將除了源節點之外到源節點的距離設定為無窮大,本身設定成0,依次訪問n-1個點,以該點為基準進行鬆弛
import time
begin=time.clock()
juzhen=[
[0,4,2,5,999,999,999,999,999,999],
[999,0,999,999,7,5,999,999,999,999],
[999,999,0,999,999,9,999,999,999,999],
[999,999,999,0,2,999,7,999,999,999],
[999,999,999,999,0,999,999,4,999,999],
[999,999,999,999,999,0,999,999,999,6],
[999,999,999,999,999,999,0,999,3,999],
[999,999,999,999,999,999,999,0,999,7],
[999,999,999,999,999,999,999,999,0,8],
[999,999,999,999,999,999,999,999,999,0]
]isornotfuquanhuilu=0
distance=[999 for i in range(10)]
distance[0]=0
for i in range(10):
for j in range(10):
if(distance[i]!=999 and distance[i]+juzhen[i][j]spfa演算法:(分支界限法求最短路徑)
"""spfa演算法是bellman-ford演算法的優化版本
只有那些在前一遍鬆弛中改變了距離估計值的點,才可能引起他們的鄰接點的距離估計值的改變。
"""import time
begin=time.clock()
juzhen=[
[0,4,2,5,999,999,999,999,999,999],
[999,0,999,999,7,5,999,999,999,999],
[999,999,0,999,999,9,999,999,999,999],
[999,999,999,0,2,999,7,999,999,999],
[999,999,999,999,0,999,999,4,999,999],
[999,999,999,999,999,0,999,999,999,6],
[999,999,999,999,999,999,0,999,3,999],
[999,999,999,999,999,999,999,0,999,7],
[999,999,999,999,999,999,999,999,0,8],
[999,999,999,999,999,999,999,999,999,0]
]distance=[999 for i in range(10)]
used=[0 for i in range(10)]
q=[0 for i in range(1000)]
distance[0]=0
used[0]=1
head=0
tail=1
q[tail]=0
while(headdistance[v]+juzhen[v][i]):
distance[i]=distance[v]+juzhen[v][i]
if(used[i]==0):
tail+=1
q[tail]=i
used[i]=1
end=time.clock()
for i in range(10):
print(distance[i])
print(end-begin)
單源最短路徑
include define max 999 define maxverts 10 typedef struct graph void chushi graph g void dij graph int key,int int int main for i 1 i g.numverts i dij ...
單源最短路徑
最優子結構 最短路徑的子路徑也是最短路徑,動態規劃和貪心演算法的乙個重要指標。環路 一條最短路徑不可能包含環路 1 環路權重為負,如果有一條環路權重為負,則不存在最短路徑 2 環路權重為零,如果包含該環路,則將該環路去掉即可 3 環路權重為正,去掉改環路可以得到更短的路徑,因此不可能是最短路徑 最短...
單源最短路徑
單源最短路徑問題,即在圖中求出給定頂點到其他任一頂點的最短路徑。1.最短路徑的最優子結構性質 該性質描述為 如果p i,j 是從頂點i到j的最短路徑,k和s是這條路徑上的乙個中間頂點,那麼p k,s 必定是從k到s的最短路徑。證明 假設p i,j 是從頂點i到j的最短路徑,則有p i,j p i,k...