ダイクストラの最短経路アルゴリズム

 

import sys 
  
class Graph(): 
  
    def __init__(self, vertices): 
        self.V = vertices  #number of vertices
        self.graph = [[0 for column in range(vertices)]  #used for adjacent matrix 
                    for row in range(vertices)] 
   
    def min_d(self, dist, inspt): #to find minimum distance
        min = sys.maxsize 
        for v in range(self.V): 
            if dist[v] < min and inspt[v] == False: #inspt[v] == False,to determine whether the vertices has been included in the shorted path tree.
                min = dist[v] 
                index=v
        return index

    def dijkstra(self, start): 
        dist = [sys.maxsize] * self.V 
        dist[start] = 0
        inspt = [False] * self.V 
        print("Vertex \tDistance from Source")
        for i in range(self.V):
            u = self.min_d(dist,inspt) 
            print(chr(u+65), "\t", dist[u])#print the result
            inspt[u] = True
            for v in range(self.V): 
                if self.graph[u][v] > 0 and inspt[v] == False and dist[v] > dist[u] + self.graph[u][v]: 
                        dist[v] = dist[u] + self.graph[u][v] 
  

g = Graph(12) 
g.graph = [[0, 6, 0, 0, 10, 11, 0, 0, 0, 0, 0, 0], 
        [6, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
        [0, 8, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 3, 9, 0, 0, 0, 0], 
        [10, 0, 0, 0, 0, 0, 0, 0, 7, 5, 0, 0], 
        [11, 0, 0, 0, 0, 0, 6, 0, 0, 0, 9, 0], 
        [0, 0, 7, 3, 0, 6, 0, 5, 0, 0, 2, 0], 
        [0, 0, 0, 9, 0, 0, 5, 0, 0, 0, 3, 5], 
        [0, 0, 0, 0, 7, 0, 0, 0, 0, 2, 0, 0],
        [0, 0, 0, 0, 5, 0, 0, 0, 2, 0, 3, 0],  
        [0, 0, 0, 0, 0, 9, 2, 3, 0, 3, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0]] 
  
g.dijkstra(0)

でる:

ソースからの頂点の距離
0
B 6
E 10
F 11
C 14
J 15
G 17
I 17
K 18
D 20
H 21
L 26

公開された128元の記事 ウォン称賛90 ビュー4886

おすすめ

転載: blog.csdn.net/weixin_45405128/article/details/102657983
おすすめ