박권수

complete Dijkstra Algorithm : check another example = correct

......@@ -59,9 +59,13 @@ def Kruskal(graph) :
return F
#Dijkstra Algorithm : input = graph
def dijkstra(w) :
#Dijkstra Algorithm : input = graph / output : F = saving arc, save_length = minimum length
def Dijkstra(w, save_length) :
# n = size of w
n = len(w)
#initialize save_length
for i in range(0, n) :
save_length.append(0)
#touch[i] = v1에서 vi로 가기 위한 최단 경로상의 마지막 정점, 즉 v(i-1)
touch = list()
......@@ -71,8 +75,40 @@ def dijkstra(w) :
length.append(0)
for i in range(1, n) :
touch[i] = i
length[i] = w[0][i]
touch.append(0)
length.append(w[0][i])
#F = output
F = set()
#repeat (n - 1) times
index = 0
while index < n - 1 :
min = 1000 #min = infinite
#initialize vnear : 0
vnear = 0
for i in range(1, n) :
if (length[i] >= 0 and length[i] < min) :
min = length[i]
vnear = i
#F에 이음선 e = (touch[vnear], vnear)를 추가한다.
F.add((touch[vnear], vnear))
for i in range(1, n) :
if(length[vnear] + w[vnear][i] < length[i]) :
length[i] = length[vnear] + w[vnear][i]
touch[i] = vnear
#이미 vnear를 거쳐간 이후에는 save_length를 더이상 업데이트 할 필요가 없다.
if(length[i] >= 0) :
save_length[i] = length[i]
length[vnear] = -1
index += 1
return F
......@@ -91,11 +127,22 @@ graph = {
])
}
#mst = result of applying Kruskal Algorithm
mst = Kruskal(graph)
print('Kruskal Algorithm : ', "\n", mst)
#kruskal = result of applying Kruskal Algorithm
kruskal = Kruskal(graph)
print('Kruskal Algorithm : \n', kruskal)
print('\n')
#Dijkstra Algorithm
inf = 1000
w = [[0,7,4,6,1],[inf,0,inf,inf,inf],
[inf,2,0,5,inf], [inf,3,inf,0,inf], [inf,inf,inf,1,0]]
#save_length : saving minimum length
save_length = list()
dijkstra = Dijkstra(w, save_length)
print('Dijkstra Algorithm : \n', dijkstra)
print('Dijkstra Length : \n', save_length)
......