1. 程式人生 > >Python-通過Dijkstra計算兩點之間的最短路徑

Python-通過Dijkstra計算兩點之間的最短路徑

文章是基於http://blog.csdn.net/playboyno/article/details/7832437的實現程式碼進行修改,最終實現計算兩點之間的最短路徑並把經過的點記錄下來。

1.圖和連結中的一樣。


2.程式碼

'''
file: py_Dijkstra.py


S= [{'index': 1, 'val': 0}, {'index': 3, 'val': 15}, {'index': 2, 'val': 25}, {'index': 6, 'val': 30}, {'index': 5, 'val': 40}, {'index': 4, 'val': 50}]
dist= [0, 25, 15, 50, 40, 30]


'''
#############################################
debug=0
MAX_NUM=10000
v_num=6
end=5
S=[]#[{'index': 1, 'val': 0},...]
dist=[]
pre={1:1,2:2,3:3,4:4,5:5,6:6}
route=[]
edge=[
    [0,30,15,MAX_NUM,MAX_NUM,MAX_NUM],
    [5,0,MAX_NUM,MAX_NUM,20,30],
    [MAX_NUM,10,0,MAX_NUM,MAX_NUM,15],
    [MAX_NUM,MAX_NUM,MAX_NUM,0,MAX_NUM,MAX_NUM],
    [MAX_NUM,MAX_NUM,MAX_NUM,10,0,MAX_NUM],
    [MAX_NUM,MAX_NUM,MAX_NUM,30,10,0]
]


#########################initial min route
def init(start):
    if(debug):
        print("[init]")
    S.append({'index':start,'val':0})
    i=0
    min_dist=10000#
    while(i<v_num):
        dist.append(edge[start-1][i])
        #find Precursor node of start
        if edge[start-1][i]!=0 and min_dist>edge[start-1][i]:
            min_dist=edge[start-1][i]
            pre[i+1]=start
        i=i+1


######################
def v_in_S(v):
    i=0
    while(i<len(S)):
        if(v==S[i]['index']):
            return "YES"
        i=i+1
    
    return "NO"


######################Add point and weight to S
def get_min():
    if(debug):
        print("[get_min]")
    if(len(dist)<1):
        return {'index':-1,'val':0}
    i=0
    min_val=MAX_NUM
    min_index=0
    while(i<len(dist)):
        if(v_in_S(i+1)=="NO"):
            if(dist[i] < MAX_NUM and dist[i] > 0 and min_val>dist[i]):
                min_val=dist[i]
                min_index=i
        i=i+1
    return {'index':min_index+1,'val':min_val}


######################Update min weight value or min route
def update_dist():
    tmp_index=S[len(S)-1]['index']
    tmp_val=S[len(S)-1]['val']
    if(debug):
        print("[update_dist]","tmp_index=",tmp_index,";tmp_val=",tmp_val)    
    i=0
    while(i<v_num):
        if(v_in_S(i+1)=="NO"):
            i_dist=tmp_val+edge[tmp_index-1][i]
            if(debug):
                print("i=",i,";i_dist=",i_dist)
            if(dist[i]>i_dist):
                dist[i]=i_dist
                pre[i+1]=tmp_index
        i=i+1
    if(debug):
        print("after update dist:dist=",dist)
    
######################
def process():
    if(debug):    
        print("[process]")
    i=0
    S_len=len(S)
    while(v_num != S_len and i<v_num):
        min_vertex=get_min()
        if(debug):
            print("i=",i,";min_vertex=",min_vertex)        
            print("len(S)=",len(S),";S=",S)
        if(min_vertex['index']>0):
            if(debug):
                print("----BEFORE append:   len(S)=",len(S),";S=",S)
            S.append(min_vertex)
            if(debug):
                print("====AFTER append:   len(S)=",len(S),";S=",S)            
            update_dist()
        i=i+1
        S_len=len(S)


######################
def py_Dijkstra(start,end):
    init(start)
    print "Initial:\n ","\t start=",start,"\n\t S=",S,"\n\t dist=",dist
    process()
    print "Result:\n","\tS=",S,"\n\tdist=",dist
    #print pre
    route.append(end)
    tem=end
    while pre[tem]!=start:
        route.insert(0,pre[tem])
        tem=pre[tem]
    route.insert(0,start)
    print 'route:',route
#############################################
if(__name__=="__main__"):
    py_Dijkstra(1,4)


</pre><pre name="code" class="python">
3.結果
Initial:
  	 start= 1 
	 S= [{'index': 1, 'val': 0}] 
	 dist= [0, 30, 15, 10000, 10000, 10000]
Result:
	S= [{'index': 1, 'val': 0}, {'index': 3, 'val': 15}, {'index': 2, 'val': 25}, {'index': 6, 'val': 30}, {'index': 5, 'val': 40}, {'index': 4, 'val': 50}] 
	dist= [0, 25, 15, 50, 40, 30]
route: [1, 3, 6, 5, 4]