Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit af08a67

Browse files
Reshad-Hasanpoyea
authored andcommitted
added the dijkstra algorithm (TheAlgorithms#704)
1 parent 6f28333 commit af08a67

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎graphs/dijkstra.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""pseudo-code"""
2+
3+
"""
4+
DIJKSTRA(graph G, start vertex s,destination vertex d):
5+
// all nodes initially unexplored
6+
let H = min heap data structure, initialized with 0 and s [here 0 indicates the distance from start vertex]
7+
while H is non-empty:
8+
remove the first node and cost of H, call it U and cost
9+
if U is not explored
10+
mark U as explored
11+
if U is d:
12+
return cost // total cost from start to destination vertex
13+
for each edge(U, V): c=cost of edge(u,V) // for V in graph[U]
14+
if V unexplored:
15+
next=cost+c
16+
add next,V to H (at the end)
17+
"""
18+
import heapq
19+
20+
21+
def dijkstra(graph, start, end):
22+
heap = [(0, start)] # cost from start node,end node
23+
visited = []
24+
while heap:
25+
(cost, u) = heapq.heappop(heap)
26+
if u in visited:
27+
continue
28+
visited.append(u)
29+
if u == end:
30+
return cost
31+
for v, c in G[u]:
32+
if v in visited:
33+
continue
34+
next = cost + c
35+
heapq.heappush(heap, (next, v))
36+
return (-1, -1)
37+
38+
39+
G = {'A': [['B', 2], ['C', 5]],
40+
'B': [['A', 2], ['D', 3], ['E', 1]],
41+
'C': [['A', 5], ['F', 3]],
42+
'D': [['B', 3]],
43+
'E': [['B', 1], ['F', 3]],
44+
'F': [['C', 3], ['E', 3]]}
45+
46+
shortDistance = dijkstra(G, 'E', 'C')
47+
print(shortDistance)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /