박권수

complete Dijkstra Algorithm : check another example = correct

...@@ -59,9 +59,13 @@ def Kruskal(graph) : ...@@ -59,9 +59,13 @@ def Kruskal(graph) :
59 59
60 return F 60 return F
61 61
62 -#Dijkstra Algorithm : input = graph 62 +#Dijkstra Algorithm : input = graph / output : F = saving arc, save_length = minimum length
63 -def dijkstra(w) : 63 +def Dijkstra(w, save_length) :
64 + # n = size of w
64 n = len(w) 65 n = len(w)
66 + #initialize save_length
67 + for i in range(0, n) :
68 + save_length.append(0)
65 69
66 #touch[i] = v1에서 vi로 가기 위한 최단 경로상의 마지막 정점, 즉 v(i-1) 70 #touch[i] = v1에서 vi로 가기 위한 최단 경로상의 마지막 정점, 즉 v(i-1)
67 touch = list() 71 touch = list()
...@@ -71,8 +75,40 @@ def dijkstra(w) : ...@@ -71,8 +75,40 @@ def dijkstra(w) :
71 length.append(0) 75 length.append(0)
72 76
73 for i in range(1, n) : 77 for i in range(1, n) :
74 - touch[i] = i 78 + touch.append(0)
75 - length[i] = w[0][i] 79 + length.append(w[0][i])
80 +
81 + #F = output
82 + F = set()
83 +
84 + #repeat (n - 1) times
85 + index = 0
86 + while index < n - 1 :
87 + min = 1000 #min = infinite
88 + #initialize vnear : 0
89 + vnear = 0
90 + for i in range(1, n) :
91 + if (length[i] >= 0 and length[i] < min) :
92 + min = length[i]
93 + vnear = i
94 +
95 + #F에 이음선 e = (touch[vnear], vnear)를 추가한다.
96 + F.add((touch[vnear], vnear))
97 +
98 + for i in range(1, n) :
99 + if(length[vnear] + w[vnear][i] < length[i]) :
100 + length[i] = length[vnear] + w[vnear][i]
101 + touch[i] = vnear
102 + #이미 vnear를 거쳐간 이후에는 save_length를 더이상 업데이트 할 필요가 없다.
103 + if(length[i] >= 0) :
104 + save_length[i] = length[i]
105 +
106 +
107 + length[vnear] = -1
108 + index += 1
109 +
110 + return F
111 +
76 112
77 113
78 114
...@@ -91,11 +127,22 @@ graph = { ...@@ -91,11 +127,22 @@ graph = {
91 ]) 127 ])
92 } 128 }
93 129
94 -#mst = result of applying Kruskal Algorithm 130 +#kruskal = result of applying Kruskal Algorithm
95 -mst = Kruskal(graph) 131 +kruskal = Kruskal(graph)
96 -print('Kruskal Algorithm : ', "\n", mst) 132 +print('Kruskal Algorithm : \n', kruskal)
133 +
134 +print('\n')
135 +
97 136
98 #Dijkstra Algorithm 137 #Dijkstra Algorithm
99 inf = 1000 138 inf = 1000
100 w = [[0,7,4,6,1],[inf,0,inf,inf,inf], 139 w = [[0,7,4,6,1],[inf,0,inf,inf,inf],
101 [inf,2,0,5,inf], [inf,3,inf,0,inf], [inf,inf,inf,1,0]] 140 [inf,2,0,5,inf], [inf,3,inf,0,inf], [inf,inf,inf,1,0]]
141 +
142 +#save_length : saving minimum length
143 +save_length = list()
144 +
145 +dijkstra = Dijkstra(w, save_length)
146 +print('Dijkstra Algorithm : \n', dijkstra)
147 +print('Dijkstra Length : \n', save_length)
148 +
......