Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
Python/graphs/dijkstra_algorithm.py at master · python3/Python · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
Uh oh!
There was an error while loading.
Please reload this page
.
python3
/
Python
Public
forked from
TheAlgorithms/Python
Notifications
You must be signed in to change notification settings
Fork
5
Star
11
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Files
Expand file tree
master
Breadcrumbs
Python
/
graphs
/
dijkstra_algorithm.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
212 lines (185 loc) · 6.51 KB
master
Breadcrumbs
Python
/
graphs
/
dijkstra_algorithm.py
Copy path
Top
File metadata and controls
Code
Blame
212 lines (185 loc) · 6.51 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# Title: Dijkstra's Algorithm for finding single source shortest path from scratch
# Author: Shubham Malik
# References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
from
__future__
import
print_function
import
math
import
sys
# For storing the vertex set to retreive node with the lowest distance
class
PriorityQueue
:
# Based on Min Heap
def
__init__
(
self
):
self
.
cur_size
=
0
self
.
array
=
[]
self
.
pos
=
{}
# To store the pos of node in array
def
isEmpty
(
self
):
return
self
.
cur_size
==
0
def
min_heapify
(
self
,
idx
):
lc
=
self
.
left
(
idx
)
rc
=
self
.
right
(
idx
)
if
lc
<
self
.
cur_size
and
self
.
array
(
lc
)[
0
]
<
self
.
array
(
idx
)[
0
]:
smallest
=
lc
else
:
smallest
=
idx
if
rc
<
self
.
cur_size
and
self
.
array
(
rc
)[
0
]
<
self
.
array
(
smallest
)[
0
]:
smallest
=
rc
if
smallest
!=
idx
:
self
.
swap
(
idx
,
smallest
)
self
.
min_heapify
(
smallest
)
def
insert
(
self
,
tup
):
# Inserts a node into the Priority Queue
self
.
pos
[
tup
[
1
]]
=
self
.
cur_size
self
.
cur_size
+=
1
self
.
array
.
append
((
sys
.
maxsize
,
tup
[
1
]))
self
.
decrease_key
((
sys
.
maxsize
,
tup
[
1
]),
tup
[
0
])
def
extract_min
(
self
):
# Removes and returns the min element at top of priority queue
min_node
=
self
.
array
[
0
][
1
]
self
.
array
[
0
]
=
self
.
array
[
self
.
cur_size
-
1
]
self
.
cur_size
-=
1
self
.
min_heapify
(
1
)
del
self
.
pos
[
min_node
]
return
min_node
def
left
(
self
,
i
):
# returns the index of left child
return
2
*
i
+
1
def
right
(
self
,
i
):
# returns the index of right child
return
2
*
i
+
2
def
par
(
self
,
i
):
# returns the index of parent
return
math
.
floor
(
i
/
2
)
def
swap
(
self
,
i
,
j
):
# swaps array elements at indices i and j
# update the pos{}
self
.
pos
[
self
.
array
[
i
][
1
]]
=
j
self
.
pos
[
self
.
array
[
j
][
1
]]
=
i
temp
=
self
.
array
[
i
]
self
.
array
[
i
]
=
self
.
array
[
j
]
self
.
array
[
j
]
=
temp
def
decrease_key
(
self
,
tup
,
new_d
):
idx
=
self
.
pos
[
tup
[
1
]]
# assuming the new_d is atmost old_d
self
.
array
[
idx
]
=
(
new_d
,
tup
[
1
])
while
idx
>
0
and
self
.
array
[
self
.
par
(
idx
)][
0
]
>
self
.
array
[
idx
][
0
]:
self
.
swap
(
idx
,
self
.
par
(
idx
))
idx
=
self
.
par
(
idx
)
class
Graph
:
def
__init__
(
self
,
num
):
self
.
adjList
=
{}
# To store graph: u -> (v,w)
self
.
num_nodes
=
num
# Number of nodes in graph
# To store the distance from source vertex
self
.
dist
=
[
0
]
*
self
.
num_nodes
self
.
par
=
[
-
1
]
*
self
.
num_nodes
# To store the path
def
add_edge
(
self
,
u
,
v
,
w
):
# Edge going from node u to v and v to u with weight w
# u (w)-> v, v (w) -> u
# Check if u already in graph
if
u
in
self
.
adjList
.
keys
():
self
.
adjList
[
u
].
append
((
v
,
w
))
else
:
self
.
adjList
[
u
]
=
[(
v
,
w
)]
# Assuming undirected graph
if
v
in
self
.
adjList
.
keys
():
self
.
adjList
[
v
].
append
((
u
,
w
))
else
:
self
.
adjList
[
v
]
=
[(
u
,
w
)]
def
show_graph
(
self
):
# u -> v(w)
for
u
in
self
.
adjList
:
print
(
u
,
'->'
,
' -> '
.
join
(
str
(
"{}({})"
.
format
(
v
,
w
))
for
v
,
w
in
self
.
adjList
[
u
]))
def
dijkstra
(
self
,
src
):
# Flush old junk values in par[]
self
.
par
=
[
-
1
]
*
self
.
num_nodes
# src is the source node
self
.
dist
[
src
]
=
0
Q
=
PriorityQueue
()
Q
.
insert
((
0
,
src
))
# (dist from src, node)
for
u
in
self
.
adjList
.
keys
():
if
u
!=
src
:
self
.
dist
[
u
]
=
sys
.
maxsize
# Infinity
self
.
par
[
u
]
=
-
1
while
not
Q
.
isEmpty
():
u
=
Q
.
extract_min
()
# Returns node with the min dist from source
# Update the distance of all the neighbours of u and
# if their prev dist was INFINITY then push them in Q
for
v
,
w
in
self
.
adjList
[
u
]:
new_dist
=
self
.
dist
[
u
]
+
w
if
self
.
dist
[
v
]
>
new_dist
:
if
self
.
dist
[
v
]
==
sys
.
maxsize
:
Q
.
insert
((
new_dist
,
v
))
else
:
Q
.
decrease_key
((
self
.
dist
[
v
],
v
),
new_dist
)
self
.
dist
[
v
]
=
new_dist
self
.
par
[
v
]
=
u
# Show the shortest distances from src
self
.
show_distances
(
src
)
def
show_distances
(
self
,
src
):
print
(
"Distance from node: {}"
.
format
(
src
))
for
u
in
range
(
self
.
num_nodes
):
print
(
'Node {} has distance: {}'
.
format
(
u
,
self
.
dist
[
u
]))
def
show_path
(
self
,
src
,
dest
):
# To show the shortest path from src to dest
# WARNING: Use it *after* calling dijkstra
path
=
[]
cost
=
0
temp
=
dest
# Backtracking from dest to src
while
self
.
par
[
temp
]
!=
-
1
:
path
.
append
(
temp
)
if
temp
!=
src
:
for
v
,
w
in
self
.
adjList
[
temp
]:
if
v
==
self
.
par
[
temp
]:
cost
+=
w
break
temp
=
self
.
par
[
temp
]
path
.
append
(
src
)
path
.
reverse
()
print
(
'----Path to reach {} from {}----'
.
format
(
dest
,
src
))
for
u
in
path
:
print
(
'{}'
.
format
(
u
),
end
=
' '
)
if
u
!=
dest
:
print
(
'-> '
,
end
=
''
)
print
(
'
\n
Total cost of path: '
,
cost
)
if
__name__
==
'__main__'
:
graph
=
Graph
(
9
)
graph
.
add_edge
(
0
,
1
,
4
)
graph
.
add_edge
(
0
,
7
,
8
)
graph
.
add_edge
(
1
,
2
,
8
)
graph
.
add_edge
(
1
,
7
,
11
)
graph
.
add_edge
(
2
,
3
,
7
)
graph
.
add_edge
(
2
,
8
,
2
)
graph
.
add_edge
(
2
,
5
,
4
)
graph
.
add_edge
(
3
,
4
,
9
)
graph
.
add_edge
(
3
,
5
,
14
)
graph
.
add_edge
(
4
,
5
,
10
)
graph
.
add_edge
(
5
,
6
,
2
)
graph
.
add_edge
(
6
,
7
,
1
)
graph
.
add_edge
(
6
,
8
,
6
)
graph
.
add_edge
(
7
,
8
,
7
)
graph
.
show_graph
()
graph
.
dijkstra
(
0
)
graph
.
show_path
(
0
,
4
)
# OUTPUT
# 0 -> 1(4) -> 7(8)
# 1 -> 0(4) -> 2(8) -> 7(11)
# 7 -> 0(8) -> 1(11) -> 6(1) -> 8(7)
# 2 -> 1(8) -> 3(7) -> 8(2) -> 5(4)
# 3 -> 2(7) -> 4(9) -> 5(14)
# 8 -> 2(2) -> 6(6) -> 7(7)
# 5 -> 2(4) -> 3(14) -> 4(10) -> 6(2)
# 4 -> 3(9) -> 5(10)
# 6 -> 5(2) -> 7(1) -> 8(6)
# Distance from node: 0
# Node 0 has distance: 0
# Node 1 has distance: 4
# Node 2 has distance: 12
# Node 3 has distance: 19
# Node 4 has distance: 21
# Node 5 has distance: 11
# Node 6 has distance: 9
# Node 7 has distance: 8
# Node 8 has distance: 14
# ----Path to reach 4 from 0----
# 0 -> 7 -> 6 -> 5 -> 4
# Total cost of path: 21
You can’t perform that action at this time.