ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://www.w3schools.com/dsa/dsa_algo_graphs_dijkstra.php |
| Last Crawled | 2026-04-09 07:05:06 (1 day ago) |
| First Indexed | 2024-01-30 21:46:58 (2 years ago) |
| HTTP Status Code | 200 |
| Meta Title | DSA Dijkstra's Algorithm |
| Meta Description | Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML. |
| Meta Canonical | null |
| Boilerpipe Text | DSA
Dijkstra's Algorithm
Dijkstra's shortest path algorithm was invented in 1956 by the Dutch computer scientist Edsger W. Dijkstra during a twenty minutes coffee break, while out shopping with his fiancée in Amsterdam.
The reason for inventing the algorithm was to test a new computer called ARMAC.
Dijkstra's Algorithm
Dijkstra's algorithm finds the shortest path from one vertex to all other vertices.
It does so by repeatedly selecting the nearest unvisited vertex and calculating the distance to all the unvisited neighboring vertices.
Dijkstra's algorithm is often considered to be the most straightforward algorithm for solving the shortest path problem.
Dijkstra's algorithm is used for solving single-source shortest path problems for directed or undirected paths. Single-source means that one vertex is chosen to be the start, and the algorithm will find the shortest path from that vertex to all other vertices.
Dijkstra's algorithm does not work for graphs with negative edges. For graphs with negative edges, the Bellman-Ford algorithm that is described on the next page, can be used instead.
To find the shortest path, Dijkstra's algorithm needs to know which vertex is the source, it needs a way to mark vertices as visited, and it needs an overview of the current shortest distance to each vertex as it works its way through the graph, updating these distances when a shorter distance is found.
How it works:
Set initial distances for all vertices: 0 for the source vertex, and infinity for all the other.
Choose the unvisited vertex with the shortest distance from the start to be the current vertex. So the algorithm will always start with the source as the current vertex.
For each of the current vertex's unvisited neighbor vertices, calculate the distance from the source and update the distance if the new, calculated, distance is lower.
We are now done with the current vertex, so we mark it as visited. A visited vertex is not checked again.
Go back to step 2 to choose a new current vertex, and keep repeating these steps until all vertices are visited.
In the end we are left with the shortest path from the source vertex to every other vertex in the graph.
In the animation above, when a vertex is marked as visited, the vertex and its edges become faded to indicate that Dijkstra's algorithm is now done with that vertex, and will not visit it again.
Note:
This basic version of Dijkstra's algorithm gives us the value of the shortest path cost to every vertex, but not what the actual path is. So for example, in the animation above, we get the shortest path cost value 10 to vertex F, but the algorithm does not give us which vertices (D->E->C->D->F) that make up this shortest path. We will add this functionality further down here on this page.
A Detailed Dijkstra Simulation
Run the simulation below to get a more detailed understanding of how Dijkstra's algorithm runs on a specific graph, finding the shortest distances from vertex D.
This simulation shows how distances are calculated from vertex D to all other vertices, by always choosing the next vertex to be the closest unvisited vertex from the starting point.
Follow the step-by-step description below to get all the details of how Dijkstra's algorithm calculates the shortest distances.
Manual Run Through
Consider the Graph below.
F
2
5
3
4
5
2
B
C
5
5
2
A
4
4
E
D
G
We want to find the shortest path from the source vertex D to all other vertices, so that for example the shortest path to C is D->E->C, with path weight 2+4=6.
To find the shortest path, Dijkstra's algorithm uses an array with the distances to all other vertices, and initially sets these distances to infinite, or a very big number. And the distance to the vertex we start from (the source) is set to 0.
distances
=
[
inf
,
inf
,
inf
,
0
,
inf
,
inf
,
inf
]
#vertices [ A , B , C , D, E , F , G ]
The image below shows the initial infinite distances to other vertices from the starting vertex D. The distance value for vertex D is 0 because that is the starting point.
inf
F
2
5
3
4
5
2
inf
B
inf
C
5
5
2
inf
A
4
4
inf
E
0
D
inf
G
Dijkstra's algorithm then sets vertex D as the current vertex, and looks at the distance to the adjacent vertices. Since the initial distance to vertices A and E is infinite, the new distance to these are updated with the edge weights. So vertex A gets the distance changed from inf to 4, and vertex E gets the distance changed to 2. As mentioned on the previous page, updating the distance values in this way is called 'relaxing'.
inf
F
2
5
3
4
5
2
inf
B
inf
C
5
5
2
4
A
4
4
2
E
0
D
inf
G
After relaxing vertices A and E, vertex D is considered visited, and will not be visited again.
The next vertex to be chosen as the current vertex must the vertex with the shortest distance to the source vertex (vertex D), among the previously unvisited vertices. Vertex E is therefore chosen as the current vertex after vertex D.
inf
F
2
5
3
4
5
2
inf
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
The distance to all adjacent and not previously visited vertices from vertex E must now be calculated, and updated if needed.
The calculated distance from D to vertex A, via E, is 2+4=6. But the current distance to vertex A is already 4, which is lower, so the distance to vertex A is not updated.
The distance to vertex C is calculated to be 2+4=6, which is less than infinity, so the distance to vertex C is updated.
Similarly, the distance to node G is calculated and updated to be 2+5=7.
The next vertex to be visited is vertex A because it has the shortest distance from D of all the unvisited vertices.
inf
F
2
5
3
4
5
2
inf
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
The calculated distance to vertex C, via A, is 4+3=7, which is higher than the already set distance to vertex C, so the distance to vertex C is not updated.
Vertex A is now marked as visited, and the next current vertex is vertex C because that has the lowest distance from vertex D between the remaining unvisited vertices.
11
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
Vertex F gets updated distance 6+5=11, and vertex B gets updated distance 6+2=8.
Calculated distance to vertex G via vertex C is 6+5=11 which is higher than the already set distance of 7, so distance to vertex G is not updated.
Vertex C is marked as visited, and the next vertex to be visited is G because is has the lowest distance between the remaining unvisited vertices.
11
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
Vertex F already has a distance of 11. This is lower than the calculated distance from G, which is 7+5=12, so the distance to vertex F is not updated.
Vertex G is marked as visited, and B becomes the current vertex because it has the lowest distance of the remaining unvisited vertices.
10
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
The new distance to F via B is 8+2=10, because it is lower than F's existing distance of 11.
Vertex B is marked as visited, and there is nothing to check for the last unvisited vertex F, so Dijkstra's algorithm is finished.
Every vertex has been visited only once, and the result is the lowest distance from the source vertex D to every other vertex in the graph.
Implementation of Dijkstra's Algorithm
To implement Dijkstra's algorithm, we create a
Graph
class. The
Graph
represents the graph with its vertices and edges:
class
Graph
:
def
__init__
(
self
,
size
)
:
self
.
adj_matrix
=
[
[
0
]
*
size
for
_
in
range
(
size
)
]
self
.
size
=
size
self
.
vertex_data
=
[
''
]
*
size
def
add_edge
(
self
,
u
,
v
,
weight
)
:
if
0
<=
u
<
self
.
size
and
0
<=
v
<
self
.
size
:
self
.
adj_matrix
[
u
]
[
v
]
=
weight
self
.
adj_matrix
[
v
]
[
u
]
=
weight
# For undirected graph
def
add_vertex_data
(
self
,
vertex
,
data
)
:
if
0
<=
vertex
<
self
.
size
:
self
.
vertex_data
[
vertex
]
=
data
Line 3:
We create the
adj_matrix
to hold all the edges and edge weights. Initial values are set to
0
.
Line 4:
size
is the number of vertices in the graph.
Line 5:
The
vertex_data
holds the names of all the vertices.
Line 7-10:
The
add_edge
method is used to add an edge from vertex
u
to vertex
v
, with edge weight
weight
.
Line 12-14:
The
add_vertex_data
method is used to add a vertex to the graph. The index where the vertex should belong is given with the
vertex
argument, and
data
is the name of the vertex.
The
Graph
class also contains the method that runs Dijkstra's algorithm:
def
dijkstra
(
self
,
start_vertex_data
)
:
start_vertex
=
self
.
vertex_data
.
index
(
start_vertex_data
)
distances
=
[
float
(
'inf'
)
]
*
self
.
size
distances
[
start_vertex
]
=
0
visited
=
[
False
]
*
self
.
size
for
_
in
range
(
self
.
size
)
:
min_distance
=
float
(
'inf'
)
u
=
None
for
i
in
range
(
self
.
size
)
:
if
not
visited
[
i
]
and
distances
[
i
]
<
min_distance
:
min_distance
=
distances
[
i
]
u
=
i
if
u
is
None
:
break
visited
[
u
]
=
True
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
and
not
visited
[
v
]
:
alt
=
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
if
alt
<
distances
[
v
]
:
distances
[
v
]
=
alt
return
distances
Line 18-19:
The initial distance is set to infinity for all vertices in the
distances
array, except for the start vertex, where the distance is 0.
Line 20:
All vertices are initially set to
False
to mark them as not visited in the
visited
array.
Line 23-28:
The next current vertex is found. Outgoing edges from this vertex will be checked to see if shorter distances can be found. It is the unvisited vertex with the lowest distance from the start.
Line 30-31:
If the next current vertex has not been found, the algorithm is finished. This means that all vertices that are reachable from the source have been visited.
Line 33:
The current vertex is set as visited before relaxing adjacent vertices. This is more effective because we avoid checking the distance to the current vertex itself.
Line 35-39:
Distances are calculated for not visited adjacent vertices, and updated if the new calculated distance is lower.
After defining the
Graph
class, the vertices and edges must be defined to initialize the specific graph, and the complete code for this Dijkstra's algorithm example looks like this:
Example
Python:
class
Graph
:
def
__init__
(
self
,
size
)
:
self
.
adj_matrix
=
[
[
0
]
*
size
for
_
in
range
(
size
)
]
self
.
size
=
size
self
.
vertex_data
=
[
''
]
*
size
def
add_edge
(
self
,
u
,
v
,
weight
)
:
if
0
<=
u
<
self
.
size
and
0
<=
v
<
self
.
size
:
self
.
adj_matrix
[
u
]
[
v
]
=
weight
self
.
adj_matrix
[
v
]
[
u
]
=
weight
# For undirected graph
def
add_vertex_data
(
self
,
vertex
,
data
)
:
if
0
<=
vertex
<
self
.
size
:
self
.
vertex_data
[
vertex
]
=
data
def
dijkstra
(
self
,
start_vertex_data
)
:
start_vertex
=
self
.
vertex_data
.
index
(
start_vertex_data
)
distances
=
[
float
(
'inf'
)
]
*
self
.
size
distances
[
start_vertex
]
=
0
visited
=
[
False
]
*
self
.
size
for
_
in
range
(
self
.
size
)
:
min_distance
=
float
(
'inf'
)
u
=
None
for
i
in
range
(
self
.
size
)
:
if
not
visited
[
i
]
and
distances
[
i
]
<
min_distance
:
min_distance
=
distances
[
i
]
u
=
i
if
u
is
None
:
break
visited
[
u
]
=
True
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
and
not
visited
[
v
]
:
alt
=
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
if
alt
<
distances
[
v
]
:
distances
[
v
]
=
alt
return
distances
g
=
Graph
(
7
)
g
.
add_vertex_data
(
0
,
'A'
)
g
.
add_vertex_data
(
1
,
'B'
)
g
.
add_vertex_data
(
2
,
'C'
)
g
.
add_vertex_data
(
3
,
'D'
)
g
.
add_vertex_data
(
4
,
'E'
)
g
.
add_vertex_data
(
5
,
'F'
)
g
.
add_vertex_data
(
6
,
'G'
)
g
.
add_edge
(
3
,
0
,
4
)
# D - A, weight 5
g
.
add_edge
(
3
,
4
,
2
)
# D - E, weight 2
g
.
add_edge
(
0
,
2
,
3
)
# A - C, weight 3
g
.
add_edge
(
0
,
4
,
4
)
# A - E, weight 4
g
.
add_edge
(
4
,
2
,
4
)
# E - C, weight 4
g
.
add_edge
(
4
,
6
,
5
)
# E - G, weight 5
g
.
add_edge
(
2
,
5
,
5
)
# C - F, weight 5
g
.
add_edge
(
2
,
1
,
2
)
# C - B, weight 2
g
.
add_edge
(
1
,
5
,
2
)
# B - F, weight 2
g
.
add_edge
(
6
,
5
,
5
)
# G - F, weight 5
# Dijkstra's algorithm from D to all vertices
print
(
"\nDijkstra's Algorithm starting from vertex D:"
)
distances
=
g
.
dijkstra
(
'D'
)
for
i
,
d
in
enumerate
(
distances
)
:
print
(
f"Distance from D to
{
g
.
vertex_data
[
i
]
}
:
{
d
}
"
)
Try it Yourself »
Dijkstra's Algorithm on Directed Graphs
To run Dijkstra's algorithm on directed graphs, very few changes are needed.
Similarly to the change we needed for
cycle detection for directed graphs
, we just need to remove one line of code so that the adjacency matrix is not symmetric anymore.
Let's implement this directed graph and run Dijkstra's algorithm from vertex D.
inf
F
2
5
3
4
5
2
inf
B
inf
C
5
5
2
inf
A
4
4
inf
E
0
D
inf
G
Here is the implementation of Dijkstra's algorithm on the directed graph, with D as the source vertex:
Example
Python:
class
Graph
:
def
__init__
(
self
,
size
)
:
self
.
adj_matrix
=
[
[
0
]
*
size
for
_
in
range
(
size
)
]
self
.
size
=
size
self
.
vertex_data
=
[
''
]
*
size
def
add_edge
(
self
,
u
,
v
,
weight
)
:
if
0
<=
u
<
self
.
size
and
0
<=
v
<
self
.
size
:
self
.
adj_matrix
[
u
]
[
v
]
=
weight
#self.adj_matrix[v][u] = weight For undirected graph
def
add_vertex_data
(
self
,
vertex
,
data
)
:
if
0
<=
vertex
<
self
.
size
:
self
.
vertex_data
[
vertex
]
=
data
def
dijkstra
(
self
,
start_vertex_data
)
:
start_vertex
=
self
.
vertex_data
.
index
(
start_vertex_data
)
distances
=
[
float
(
'inf'
)
]
*
self
.
size
distances
[
start_vertex
]
=
0
visited
=
[
False
]
*
self
.
size
for
_
in
range
(
self
.
size
)
:
min_distance
=
float
(
'inf'
)
u
=
None
for
i
in
range
(
self
.
size
)
:
if
not
visited
[
i
]
and
distances
[
i
]
<
min_distance
:
min_distance
=
distances
[
i
]
u
=
i
if
u
is
None
:
break
visited
[
u
]
=
True
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
and
not
visited
[
v
]
:
alt
=
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
if
alt
<
distances
[
v
]
:
distances
[
v
]
=
alt
return
distances
g
=
Graph
(
7
)
g
.
add_vertex_data
(
0
,
'A'
)
g
.
add_vertex_data
(
1
,
'B'
)
g
.
add_vertex_data
(
2
,
'C'
)
g
.
add_vertex_data
(
3
,
'D'
)
g
.
add_vertex_data
(
4
,
'E'
)
g
.
add_vertex_data
(
5
,
'F'
)
g
.
add_vertex_data
(
6
,
'G'
)
g
.
add_edge
(
3
,
0
,
4
)
# D -> A, weight 5
g
.
add_edge
(
3
,
4
,
2
)
# D -> E, weight 2
g
.
add_edge
(
0
,
2
,
3
)
# A -> C, weight 3
g
.
add_edge
(
0
,
4
,
4
)
# A -> E, weight 4
g
.
add_edge
(
4
,
2
,
4
)
# E -> C, weight 4
g
.
add_edge
(
4
,
6
,
5
)
# E -> G, weight 5
g
.
add_edge
(
2
,
5
,
5
)
# C -> F, weight 5
g
.
add_edge
(
1
,
2
,
2
)
# B -> C, weight 2
g
.
add_edge
(
1
,
5
,
2
)
# B -> F, weight 2
g
.
add_edge
(
6
,
5
,
5
)
# G -> F, weight 5
# Dijkstra's algorithm from D to all vertices
print
(
"Dijkstra's Algorithm starting from vertex D:\n"
)
distances
=
g
.
dijkstra
(
'D'
)
for
i
,
d
in
enumerate
(
distances
)
:
print
(
f"Shortest distance from D to
{
g
.
vertex_data
[
i
]
}
:
{
d
}
"
)
Try it Yourself »
The image below shows us the shortest distances from vertex D as calculated by Dijkstra's algorithm.
11
F
2
5
3
4
5
2
inf
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
This result is similar to the previous example using Dijkstra's algorithm on the undirected graph. However, there's a key difference: in this case, vertex B cannot be visited from D, and this means that the shortest distance from D to F is now 11, not 10, because the path can no longer go through vertex B.
Returning The Paths from Dijkstra's Algorithm
With a few adjustments, the actual shortest paths can also be returned by Dijkstra's algorithm, in addition to the shortest path values. So for example, instead of just returning that the shortest path value is 10 from vertex D to F, the algorithm can also return that the shortest path is "D->E->C->B->F".
10
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
To return the path, we create a
predecessors
array to keep the previous vertex in the shortest path for each vertex. The
predecessors
array can be used to backtrack to find the shortest path for every vertex.
Example
Python:
class
Graph
:
# ... (rest of the Graph class)
def
dijkstra
(
self
,
start_vertex_data
)
:
start_vertex
=
self
.
vertex_data
.
index
(
start_vertex_data
)
distances
=
[
float
(
'inf'
)
]
*
self
.
size
predecessors
=
[
None
]
*
self
.
size
distances
[
start_vertex
]
=
0
visited
=
[
False
]
*
self
.
size
for
_
in
range
(
self
.
size
)
:
min_distance
=
float
(
'inf'
)
u
=
None
for
i
in
range
(
self
.
size
)
:
if
not
visited
[
i
]
and
distances
[
i
]
<
min_distance
:
min_distance
=
distances
[
i
]
u
=
i
if
u
is
None
:
break
visited
[
u
]
=
True
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
and
not
visited
[
v
]
:
alt
=
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
if
alt
<
distances
[
v
]
:
distances
[
v
]
=
alt
predecessors
[
v
]
=
u
return
distances
,
predecessors
def
get_path
(
self
,
predecessors
,
start_vertex
,
end_vertex
)
:
path
=
[
]
current
=
self
.
vertex_data
.
index
(
end_vertex
)
while
current
is
not
None
:
path
.
insert
(
0
,
self
.
vertex_data
[
current
]
)
current
=
predecessors
[
current
]
if
current
==
self
.
vertex_data
.
index
(
start_vertex
)
:
path
.
insert
(
0
,
start_vertex
)
break
return
'->'
.
join
(
path
)
# Join the vertices with '->'
g
=
Graph
(
7
)
# ... (rest of the graph setup)
# Dijkstra's algorithm from D to all vertices
print
(
"Dijkstra's Algorithm starting from vertex D:\n"
)
distances
,
predecessors
=
g
.
dijkstra
(
'D'
)
for
i
,
d
in
enumerate
(
distances
)
:
path
=
g
.
get_path
(
predecessors
,
'D'
,
g
.
vertex_data
[
i
]
)
print
(
f"
{
path
}
, Distance:
{
d
}
"
)
Try it Yourself »
Line 7 and 29:
The
predecessors
array is first initialized with
None
values, then it is updated with the correct predecessor for each vertex as the shortest path values are updated.
Line 33-42:
The
get_path
method uses the
predecessors
array and returns a string with the shortest path from start to end vertex.
Dijkstra's Algorithm with a Single Destination Vertex
Let's say we are only interested in finding the shortest path between two vertices, like finding the shortest distance between vertex D and vertex F in the graph below.
inf
F
2
5
3
4
5
2
inf
B
inf
C
5
5
2
inf
A
4
4
inf
E
0
D
inf
G
5
inf
H
4
inf
I
2
inf
J
Dijkstra's algorithm is normally used for finding the shortest path from one source vertex to all other vertices in the graph, but it can also be modified to only find the shortest path from the source to a single destination vertex, by just stopping the algorithm when the destination is reached (visited).
This means that for the specific graph in the image above, Dijkstra's algorithm will stop after visiting F (the destination vertex), before visiting vertices H, I and J because they are farther away from D than F is.
Below we can see the status of the calculated distances when Dijkstra's algorithm has found the shortest distance from D to F, and stops running.
10
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
5
12
H
4
11
I
2
inf
J
In the image above, vertex F has just got updated with distance 10 from vertex B. Since F is the unvisited vertex with the lowest distance from D, it would normally be the next current vertex, but since it is the destination, the algorithm stops. If the algorithm did not stop, J would be the next vertex to get an updated distance 11+2=13, from vertex I.
The code below is Dijkstra's algorithm implemented to find the shortest path to a single destination vertex:
Example
Python:
class
Graph
:
# ... (existing methods)
def
dijkstra
(
self
,
start_vertex_data
,
end_vertex_data
)
:
start_vertex
=
self
.
vertex_data
.
index
(
start_vertex_data
)
end_vertex
=
self
.
vertex_data
.
index
(
end_vertex_data
)
distances
=
[
float
(
'inf'
)
]
*
self
.
size
predecessors
=
[
None
]
*
self
.
size
distances
[
start_vertex
]
=
0
visited
=
[
False
]
*
self
.
size
for
_
in
range
(
self
.
size
)
:
min_distance
=
float
(
'inf'
)
u
=
None
for
i
in
range
(
self
.
size
)
:
if
not
visited
[
i
]
and
distances
[
i
]
<
min_distance
:
min_distance
=
distances
[
i
]
u
=
i
if
u
is
None
or
u
==
end_vertex
:
print
(
f"Breaking out of loop. Current vertex:
{
self
.
vertex_data
[
u
]
}
"
)
print
(
f"Distances:
{
distances
}
"
)
break
visited
[
u
]
=
True
print
(
f"Visited vertex:
{
self
.
vertex_data
[
u
]
}
"
)
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
and
not
visited
[
v
]
:
alt
=
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
if
alt
<
distances
[
v
]
:
distances
[
v
]
=
alt
predecessors
[
v
]
=
u
return
distances
[
end_vertex
]
,
self
.
get_path
(
predecessors
,
start_vertex_data
,
end_vertex_data
)
# Example usage
g
=
Graph
(
7
)
# ... (rest of the graph setup)
distance
,
path
=
g
.
dijkstra
(
'D'
,
'F'
)
print
(
f"Path:
{
path
}
, Distance:
{
distance
}
"
)
Try it Yourself »
Line 20-23:
If we are about to choose the destination vertex as the current vertex and mark it as visited, it means we have already calculated the shortest distance to the destination vertex, and Dijkstra's algorithm can be stopped in this single destination case.
Time Complexity for Dijkstra's Algorithm
With
V
as the number of vertices in our graph, the time complexity for Dijkstra's algorithm is
O
(
V
2
)
The reason why we get this time complexity is that the vertex with the lowest distance must to be search for to choose the next current vertex, and that takes
O
(
V
)
time. And since this must to be done for every vertex connected to the source, we need to factor that in, and so we get time complexity
O
(
V
2
)
for Dijkstra's algorithm.
By using a Min-heap or Fibonacci-heap data structure for the distances instead (not yet explained in this tutorial), the time needed to search for the minimum distance vertex is reduced from
O
(
V
)
to
O
(
log
V
)
, which results in an improved time complexity for Dijkstra's algorithm
O
(
V
⋅
log
V
+
E
)
Where
V
is the number of vertices in the graph, and
E
is the number of edges.
The improvement we get from using a Min-heap data structure for Dijkstra's algorithm is especially good if we have a large and sparse graph, which means a graph with a large number of vertices, but not as many edges.
The implementation of Dijkstra's algorithm with the Fibonacci-heap data structure is better for dense graphs, where each vertex has an edge to almost every other vertex.
DSA Exercises
Test Yourself With Exercises
Exercise:
Using Dijkstra's algorithm to find the shortest paths from vertex C in this graph:
What is the next vertex to be visited after C is visited?
Using Dijkstra's algorithm,
the next vertex to be visited
after vertex C is vertex
.
Start the Exercise |
| Markdown | [Tutorials]("Tutorials and References") [References]("References") [Exercises]("Exercises and Quizzes") [Certificates]("Certificates")
[Menu]("Menu")
Search field
*×*
[See More]()
Sign In
[★ +1](https://profile.w3schools.com/log-in?redirect_url=https%3A%2F%2Fwww.w3schools.com%2Fdsa%2Fdsa_algo_graphs_dijkstra.php "Your W3Schools Profile")
[Get Certified](https://campus.w3schools.com/collections/course-catalog "W3Schools Certificates")
[Upgrade](https://order.w3schools.com/plans "Become a PLUS user and unlock powerful features")
[Teachers](https://www.w3schools.com/academy/index.php "Contact us about W3Schools Academy for educational institutions")
[Spaces](https://www.w3schools.com/spaces/index.php "Get Your Own Website With W3Schools Spaces")
[Bootcamps](https://www.w3schools.com/bootcamp/index.php "W3Schools Bootcamps")
[Get Certified](https://campus.w3schools.com/collections/course-catalog "W3Schools Certificates")
[Upgrade](https://order.w3schools.com/plans "Get personalized learning journey based on your current skills and goals")
[Teachers](https://www.w3schools.com/academy/index.php "Contact us about W3Schools Academy for educational institutions")
[Spaces](https://spaces.w3schools.com/ "Go to Your W3Schools Space")
[Bootcamps](https://www.w3schools.com/bootcamp/index.php "W3Schools Bootcamps")
[My W3Schools](https://pathfinder.w3schools.com/ "My W3Schools")
Tutorials
References
Exercises
Certificates
[Spaces](https://www.w3schools.com/spaces/index.php "Get Your Own Website With W3Schools Spaces")
[Get Certified](https://campus.w3schools.com/collections/course-catalog "W3Schools Certificates")
[Plus](https://order.w3schools.com/plans "Become a PLUS user and unlock powerful features")
[Bootcamps](https://www.w3schools.com/bootcamp/index.php "W3Schools Bootcamps") [Academy](https://www.w3schools.com/academy/index.php "W3Schools Academy")
All our Services
[Logout](https://profile.w3schools.com/logout "Logout")
[**](https://www.linkedin.com/company/w3schools.com/ "W3Schools on LinkedIn") [**](https://discord.com/invite/w3schools "Join the W3schools community on Discord") [**](https://www.facebook.com/w3schoolscom/ "W3Schools on Facebook") [**](https://www.instagram.com/w3schools.com_official/ "W3Schools on Instagram")
×
## **Tutorials**
Tutorials filter input
×
### HTML and CSS
[Learn HTML](https://www.w3schools.com/html/default.asp "HTML Tutorial") [Tutorial](https://www.w3schools.com/html/default.asp "HTML Tutorial") [Reference](https://www.w3schools.com/tags/default.asp "HTML Reference")
[Learn CSS](https://www.w3schools.com/css/default.asp "CSS Tutorial") [Tutorial](https://www.w3schools.com/css/default.asp "CSS Tutorial") [Reference](https://www.w3schools.com/cssref/default.asp "CSS Reference")
[Learn RWD](https://www.w3schools.com/css/css_rwd_intro.asp "Responsive Web Design Tutorial") [Tutorial](https://www.w3schools.com/css/css_rwd_intro.asp "Responsive Web Design Tutorial")
[Learn Bootstrap](https://www.w3schools.com/bootstrap/bootstrap_ver.asp "Bootstrap Tutorials") [Overview](https://www.w3schools.com/bootstrap/bootstrap_ver.asp "Bootstrap Tutorials")
[Learn W3.CSS](https://www.w3schools.com/w3css/default.asp "W3.CSS Tutorial") [Tutorial](https://www.w3schools.com/w3css/default.asp "W3.CSS Tutorial") [Reference](https://www.w3schools.com/w3css/w3css_references.asp "W3.CSS Reference")
[Learn Sass](https://www.w3schools.com/sass/default.asp "SASS Tutorial") [Tutorial](https://www.w3schools.com/sass/default.asp "SASS Tutorial") [Reference](https://www.w3schools.com/sass/sass_functions_string.asp "SASS Reference")
[Learn Colors](https://www.w3schools.com/colors/default.asp "Colors Tutorial") [Tutorial](https://www.w3schools.com/colors/default.asp "Colors Tutorial") [Reference](https://www.w3schools.com/colors/colors_fs595.asp "Colors Reference")
[Learn Icons](https://www.w3schools.com/icons/default.asp "Icons Tutorial") [Tutorial](https://www.w3schools.com/icons/default.asp "Icons Tutorial") [Reference](https://www.w3schools.com/icons/icons_reference.asp "Icons Reference")
[Learn SVG](https://www.w3schools.com/graphics/svg_intro.asp "SVG Tutorial") [Tutorial](https://www.w3schools.com/graphics/svg_intro.asp "SVG Tutorial") [Reference](https://www.w3schools.com/graphics/svg_reference.asp "SVG Reference")
[Learn Canvas](https://www.w3schools.com/graphics/canvas_intro.asp "Canvas Tutorial") [Tutorial](https://www.w3schools.com/graphics/canvas_intro.asp "Canvas Tutorial") [Reference](https://www.w3schools.com/graphics/canvas_reference.asp "Canvas Reference")
[Learn Graphics](https://www.w3schools.com/graphics/default.asp "Graphics Tutorial") [Tutorial](https://www.w3schools.com/graphics/default.asp "Graphics Tutorial")
[Learn UTF-8 and Emojis](https://www.w3schools.com/charsets/default.asp "UTF-8 and Emojis Reference") [Reference](https://www.w3schools.com/charsets/default.asp "UTF-8 and Emojis Reference")
[Learn How To](https://www.w3schools.com/howto/default.asp "How To - Code Snippets") [Tutorial](https://www.w3schools.com/howto/default.asp "How To - Code Snippets")
### Data Analytics
[Learn AI](https://www.w3schools.com/ai/default.asp "Artificial Intelligence Tutorial") [Tutorial](https://www.w3schools.com/ai/default.asp "Artificial Intelligence Tutorial")
[Learn Generative AI](https://www.w3schools.com/gen_ai/index.php "Generative AI Tutorial") [Tutorial](https://www.w3schools.com/gen_ai/index.php "Generative AI Tutorial")
[Learn ChatGPT-3.5](https://www.w3schools.com/gen_ai/chatgpt-3-5/index.php "ChatGPT-3.5 Tutorial") [Tutorial](https://www.w3schools.com/gen_ai/chatgpt-3-5/index.php "ChatGPT-3.5 Tutorial")
[Learn ChatGPT-4](https://www.w3schools.com/gen_ai/chatgpt-4/index.php "ChatGPT-4 Tutorial") [Tutorial](https://www.w3schools.com/gen_ai/chatgpt-4/index.php "ChatGPT-4 Tutorial")
[Learn Google Bard](https://www.w3schools.com/gen_ai/bard/index.php "Google Bard Tutorial") [Tutorial](https://www.w3schools.com/gen_ai/bard/index.php "Google Bard Tutorial")
[Learn Machine Learning](https://www.w3schools.com/python/python_ml_getting_started.asp "Machine Learning Tutorial") [Tutorial](https://www.w3schools.com/python/python_ml_getting_started.asp "Machine Learning Tutorial")
[Learn DSA](https://www.w3schools.com/dsa/index.php "DSA - Data Structures and Algorithms") [Tutorial](https://www.w3schools.com/dsa/index.php "DSA - Data Structures and Algorithms")
[Learn Data Science](https://www.w3schools.com/datascience/default.asp "Data Science Tutorial") [Tutorial](https://www.w3schools.com/datascience/default.asp "Data Science Tutorial")
[Learn NumPy](https://www.w3schools.com/python/numpy/default.asp "NumPy Tutorial") [Tutorial](https://www.w3schools.com/python/numpy/default.asp "NumPy Tutorial")
[Learn Pandas](https://www.w3schools.com/python/pandas/default.asp "Pandas Tutorial") [Tutorial](https://www.w3schools.com/python/pandas/default.asp "Pandas Tutorial")
[Learn SciPy](https://www.w3schools.com/python/scipy/index.php "SciPy Tutorial") [Tutorial](https://www.w3schools.com/python/scipy/index.php "SciPy Tutorial")
[Learn Matplotlib](https://www.w3schools.com/python/matplotlib_intro.asp "Matplotlib Tutorial") [Tutorial](https://www.w3schools.com/python/matplotlib_intro.asp "Matplotlib Tutorial")
[Learn Statistics](https://www.w3schools.com/statistics/index.php "Statistics Tutorial") [Tutorial](https://www.w3schools.com/statistics/index.php "Statistics Tutorial")
[Learn Excel](https://www.w3schools.com/excel/index.php "Excel Tutorial") [Tutorial](https://www.w3schools.com/excel/index.php "Excel Tutorial")
[Learn Google Sheets](https://www.w3schools.com/googlesheets/index.php "Google Sheets Tutorial") [Tutorial](https://www.w3schools.com/googlesheets/index.php "Google Sheets Tutorial")
### Web Building
[Create a Website](https://www.w3schools.com/spaces/index.php "Get Your Own Website With W3schools Spaces")
[Create a Server NEW](https://www.w3schools.com/spaces/index.php "Get Your Own Server With W3schools Spaces")
[Where To Start](https://www.w3schools.com/where_to_start.asp "Where To Start - Web Development")
[Web Templates](https://www.w3schools.com/w3css/w3css_templates.asp "Free Web Templates")
[Web Statistics](https://www.w3schools.com/browsers/default.asp "Web Statistics")
[Web Certificates](https://campus.w3schools.com/ "Certificates")
[Web Development](https://www.w3schools.com/whatis/default.asp "Web Development Roadmaps")
[Introduction to Programming](https://www.w3schools.com/programming/index.php "Introduction to Programming")
[Introduction to HTML & CSS](https://www.w3schools.com/htmlcss/default.asp "HTML & CSS")
[Code Editor](https://www.w3schools.com/tryit/default.asp "Try it - Code Editor")
[Test Your Typing Speed](https://www.w3schools.com/typingspeed/default.asp "Test Your Typing Speed")
[Play a Code Game](https://www.w3schools.com/codegame/index.html "Play a Code Game")
[Web Development Tools](https://www.w3schools.com/tools/index.php "Web Development Tools")
[Cyber Security](https://www.w3schools.com/cybersecurity/index.php "Cyber Security Tutorial")
[Accessibility](https://www.w3schools.com/accessibility/index.php "Accessibility Security Tutorial")
[Join our Newsletter](https://campus.w3schools.com/pages/newsletter "W3Schools Newsletter")
### JavaScript
[Learn JavaScript](https://www.w3schools.com/js/default.asp "JavaScript Tutorial") [Tutorial](https://www.w3schools.com/js/default.asp "JavaScript Tutorial") [Reference](https://www.w3schools.com/jsref/default.asp "JavaScript Reference")
[Learn React](https://www.w3schools.com/react/default.asp "React Tutorial") [Tutorial](https://www.w3schools.com/react/default.asp "React Tutorial")
[Learn jQuery](https://www.w3schools.com/jquery/default.asp "jQuery Tutorial") [Tutorial](https://www.w3schools.com/jquery/default.asp "jQuery Tutorial") [Reference](https://www.w3schools.com/jquery/jquery_ref_overview.asp "jQuery Reference")
[Learn Vue](https://www.w3schools.com/vue/index.php "Vue Tutorial") [Tutorial](https://www.w3schools.com/vue/index.php "Vue Tutorial") [Reference](https://www.w3schools.com/vue/vue_ref_builtin-attributes.php "Vue Reference")
[Learn Angular](https://www.w3schools.com/angular/default.asp "Angular Tutorial") [Tutorial](https://www.w3schools.com/angular/default.asp "Angular Tutorial")
[Learn AngularJS](https://www.w3schools.com/angularjs/default.asp "AngularJS Tutorial") [Tutorial](https://www.w3schools.com/angularjs/default.asp "AngularJS Tutorial") [Reference](https://www.w3schools.com/angularjs/angularjs_ref_directives.asp "AngularJS Reference")
[Learn JSON](https://www.w3schools.com/js/js_json_intro.asp "JSON Tutorial") [Tutorial](https://www.w3schools.com/js/js_json_intro.asp "JSON Tutorial") [Reference](https://www.w3schools.com/jsref/jsref_obj_json.asp "JSON Reference")
[Learn AJAX](https://www.w3schools.com/js/js_ajax_intro.asp "AJAX Tutorial") [Tutorial](https://www.w3schools.com/js/js_ajax_intro.asp "AJAX Tutorial")
[Learn AppML](https://www.w3schools.com/appml/default.asp "AppML Tutorial") [Tutorial](https://www.w3schools.com/appml/default.asp "AppML Tutorial") [Reference](https://www.w3schools.com/appml/appml_reference.asp "AppML Reference")
[Learn W3.JS](https://www.w3schools.com/w3js/default.asp "W3.JS Tutorial") [Tutorial](https://www.w3schools.com/w3js/default.asp "W3.JS Tutorial") [Reference](https://www.w3schools.com/w3js/w3js_references.asp "W3.JS Reference")
### Web Building
[Create a Website](https://www.w3schools.com/spaces/index.php "Get Your Own Website With W3schools Spaces")
[Create a Server NEW](https://www.w3schools.com/spaces/index.php "Get Your Own Server With W3schools Spaces")
[Where To Start](https://www.w3schools.com/where_to_start.asp "Where To Start - Web Development")
[Web Templates](https://www.w3schools.com/w3css/w3css_templates.asp "Free Web Templates")
[Web Statistics](https://www.w3schools.com/browsers/default.asp "Web Statistics")
[Web Certificates](https://campus.w3schools.com/ "Certificates")
[Web Development](https://www.w3schools.com/whatis/default.asp "Web Development Roadmaps")
[Introduction to Programming](https://www.w3schools.com/programming/index.php "Introduction to Programming")
[Introduction to HTML & CSS](https://www.w3schools.com/htmlcss/default.asp "HTML & CSS")
[Code Editor](https://www.w3schools.com/tryit/default.asp "Try it - Code Editor")
[Test Your Typing Speed](https://www.w3schools.com/typingspeed/default.asp "Test Your Typing Speed")
[Play a Code Game](https://www.w3schools.com/codegame/index.html "Play a Code Game")
[Web Developer Tools](https://www.w3schools.com/tools/index.php "Web Developer Tools")
[Cyber Security](https://www.w3schools.com/cybersecurity/index.php "Cyber Security Tutorial")
[Accessibility](https://www.w3schools.com/accessibility/index.php "Accessibility Security Tutorial")
[Join our Newsletter](https://campus.w3schools.com/pages/newsletter "W3Schools Newsletter")
### Backend
[Learn Python](https://www.w3schools.com/python/default.asp "Python Tutorial") [Tutorial](https://www.w3schools.com/python/default.asp "Python Tutorial") [Reference](https://www.w3schools.com/python/python_reference.asp "Python Reference")
[Learn SQL](https://www.w3schools.com/sql/default.asp "SQL Tutorial") [Tutorial](https://www.w3schools.com/sql/default.asp "SQL Tutorial") [Reference](https://www.w3schools.com/sql/sql_ref_keywords.asp "SQL Reference")
[Learn MySQL](https://www.w3schools.com/mysql/default.asp "MySQL Tutorial") [Tutorial](https://www.w3schools.com/mysql/default.asp "MySQL Tutorial") [Reference](https://www.w3schools.com/mysql/mysql_datatypes.asp "MySQL Reference")
[Learn PHP](https://www.w3schools.com/php/default.asp "PHP Tutorial") [Tutorial](https://www.w3schools.com/php/default.asp "PHP Tutorial") [Reference](https://www.w3schools.com/php/php_ref_overview.asp "PHP Reference")
[Learn Java](https://www.w3schools.com/java/default.asp "Java Tutorial") [Tutorial](https://www.w3schools.com/java/default.asp "Java Tutorial") [Reference](https://www.w3schools.com/java/java_ref_reference.asp "Java Reference")
[Learn C](https://www.w3schools.com/c/index.php "C Tutorial") [Tutorial](https://www.w3schools.com/c/index.php "C Tutorial") [Reference](https://www.w3schools.com/c/c_ref_reference.php "C Reference")
[Learn C++](https://www.w3schools.com/cpp/default.asp "C++ Tutorial") [Tutorial](https://www.w3schools.com/cpp/default.asp "C++ Tutorial") [Reference](https://www.w3schools.com/cpp/cpp_ref_reference.asp "C++ Reference")
[Learn C\#](https://www.w3schools.com/cs/index.php "C# Tutorial") [Tutorial](https://www.w3schools.com/cs/index.php "C# Tutorial")
[Learn R](https://www.w3schools.com/r/default.asp "R Tutorial") [Tutorial](https://www.w3schools.com/r/default.asp "R Tutorial")
[Learn Kotlin](https://www.w3schools.com/kotlin/index.php "Kotlin Tutorial") [Tutorial](https://www.w3schools.com/kotlin/index.php "Kotlin Tutorial")
[Learn Rust](https://www.w3schools.com/rust/index.php "Rust Tutorial") [Tutorial](https://www.w3schools.com/rust/index.php "Rust Tutorial")
[Learn Go](https://www.w3schools.com/go/index.php "Go Tutorial") [Tutorial](https://www.w3schools.com/go/index.php "Go Tutorial")
[Learn Django](https://www.w3schools.com/django/index.php "Django Tutorial") [Tutorial](https://www.w3schools.com/django/index.php "Django Tutorial") [Reference](https://www.w3schools.com/django/django_ref_template_tags.php "Django Reference")
[Learn PostgreSQL](https://www.w3schools.com/postgresql/index.php "PostgreSQL Tutorial") [Tutorial](https://www.w3schools.com/postgresql/index.php "PostgreSQL Tutorial")
[Learn TypeScript](https://www.w3schools.com/typescript/index.php "TypeScript Tutorial") [Tutorial](https://www.w3schools.com/typescript/index.php "TypeScript Reference")
[Learn ASP](https://www.w3schools.com/asp/default.asp "ASP Tutorial") [Tutorial](https://www.w3schools.com/asp/default.asp "ASP Tutorial") [Reference](https://www.w3schools.com/asp/asp_ref_vbscript_functions.asp "ASP Reference")
[Learn Node.js](https://www.w3schools.com/nodejs/default.asp "Node.js Tutorial") [Tutorial](https://www.w3schools.com/nodejs/default.asp "Node.js Tutorial") [Reference](https://www.w3schools.com/nodejs/ref_modules.asp "Node.js Reference")
[Learn Raspberry Pi](https://www.w3schools.com/nodejs/nodejs_raspberrypi.asp "Raspberry Pi Tutorial") [Tutorial](https://www.w3schools.com/nodejs/nodejs_raspberrypi.asp "Raspberry Pi Tutorial")
[Learn Swift](https://www.w3schools.com/swift/default.asp "Swift Tutorial") [Tutorial](https://www.w3schools.com/swift/default.asp "Swift Tutorial")
[Learn Git](https://www.w3schools.com/git/default.asp "Git Tutorial") [Tutorial](https://www.w3schools.com/git/default.asp "Git Tutorial")
[Learn Bash](https://www.w3schools.com/bash/index.php "Bash Tutorial") [Tutorial](https://www.w3schools.com/bash/index.php "Bash Tutorial")
[Learn MongoDB](https://www.w3schools.com/mongodb/index.php "MongoDB Tutorial") [Tutorial](https://www.w3schools.com/mongodb/index.php "MongoDB Tutorial")
[Learn AWS Cloud](https://www.w3schools.com/aws/index.php "AWS Cloud Tutorial") [Tutorial](https://www.w3schools.com/aws/index.php "AWS Cloud Tutorial")
[Learn XML](https://www.w3schools.com/xml/default.asp "XML Tutorial") [Tutorial](https://www.w3schools.com/xml/default.asp "XML Tutorial") [Reference](https://www.w3schools.com/xml/dom_nodetype.asp "XML Reference")
### Data Analytics
[Learn AI](https://www.w3schools.com/ai/default.asp "Artificial Intelligence Tutorial") [Tutorial](https://www.w3schools.com/ai/default.asp "Artificial Intelligence Tutorial")
[Learn Generative AI](https://www.w3schools.com/gen_ai/index.php "Generative AI Tutorial") [Tutorial](https://www.w3schools.com/gen_ai/index.php "Generative AI Tutorial")
[Learn ChatGPT-3.5](https://www.w3schools.com/gen_ai/chatgpt-3-5/index.php "ChatGPT-3.5 Tutorial") [Tutorial](https://www.w3schools.com/gen_ai/chatgpt-3-5/index.php "ChatGPT-3.5 Tutorial")
[Learn ChatGPT-4](https://www.w3schools.com/gen_ai/chatgpt-4/index.php "ChatGPT-4 Tutorial") [Tutorial](https://www.w3schools.com/gen_ai/chatgpt-4/index.php "ChatGPT-4 Tutorial")
[Learn Google Bard](https://www.w3schools.com/gen_ai/bard/index.php "Google Bard Tutorial") [Tutorial](https://www.w3schools.com/gen_ai/bard/index.php "Google Bard Tutorial")
[Learn Machine Learning](https://www.w3schools.com/python/python_ml_getting_started.asp "Machine Learning Tutorial") [Tutorial](https://www.w3schools.com/python/python_ml_getting_started.asp "Machine Learning Tutorial")
[Learn DSA](https://www.w3schools.com/dsa/index.php "DSA - Data Structures and Algorithms") [Tutorial](https://www.w3schools.com/dsa/index.php "DSA - Data Structures and Algorithms ")
[Learn Data Science](https://www.w3schools.com/datascience/default.asp "Data Science Tutorial") [Tutorial](https://www.w3schools.com/datascience/default.asp "Data Science Tutorial")
[Learn NumPy](https://www.w3schools.com/python/numpy/default.asp "NumPy Tutorial") [Tutorial](https://www.w3schools.com/python/numpy/default.asp "NumPy Tutorial")
[Learn Pandas](https://www.w3schools.com/python/pandas/default.asp "Pandas Tutorial") [Tutorial](https://www.w3schools.com/python/pandas/default.asp "Pandas Tutorial")
[Learn SciPy](https://www.w3schools.com/python/scipy/index.php "SciPy Tutorial") [Tutorial](https://www.w3schools.com/python/scipy/index.php "SciPy Tutorial")
[Learn Matplotlib](https://www.w3schools.com/python/matplotlib_intro.asp "Matplotlib Tutorial") [Tutorial](https://www.w3schools.com/python/matplotlib_intro.asp "Matplotlib Tutorial")
[Learn Statistics](https://www.w3schools.com/statistics/index.php "Statistics Tutorial") [Tutorial](https://www.w3schools.com/statistics/index.php "Statistics Tutorial")
[Learn Excel](https://www.w3schools.com/excel/index.php "Excel Tutorial") [Tutorial](https://www.w3schools.com/excel/index.php "Excel Tutorial")
[Learn Google Sheets](https://www.w3schools.com/googlesheets/index.php "Google Sheets Tutorial") [Tutorial](https://www.w3schools.com/googlesheets/index.php "Google Sheets Tutorial")
### Web Building
[Create a Website](https://www.w3schools.com/spaces/index.php "Get Your Own Website With W3schools Spaces")
[Create a Server NEW](https://www.w3schools.com/spaces/index.php "Get Your Own Server With W3schools Spaces")
[Where To Start](https://www.w3schools.com/where_to_start.asp "Where To Start - Web Development")
[Web Templates](https://www.w3schools.com/w3css/w3css_templates.asp "Free Web Templates")
[Web Statistics](https://www.w3schools.com/browsers/default.asp "Web Statistics")
[Web Certificates](https://campus.w3schools.com/ "Certificates")
[Web Development](https://www.w3schools.com/whatis/default.asp "Web Development Roadmaps")
[Introduction to Programming](https://www.w3schools.com/programming/index.php "Introduction to Programming")
[Introduction to HTML & CSS](https://www.w3schools.com/htmlcss/default.asp "HTML & CSS")
[Code Editor](https://www.w3schools.com/tryit/default.asp "Try it - Code Editor")
[Test Your Typing Speed](https://www.w3schools.com/typingspeed/default.asp "Test Your Typing Speed")
[Play a Code Game](https://www.w3schools.com/codegame/index.html "Play a Code Game")
[Web Developer Tools](https://www.w3schools.com/tools/index.php "Web Developer Tools")
[Cyber Security](https://www.w3schools.com/cybersecurity/index.php "Cyber Security Tutorial")
[Accessibility](https://www.w3schools.com/accessibility/index.php "Accessibility Security Tutorial")
[Join our Newsletter](https://campus.w3schools.com/pages/newsletter "W3Schools Newsletter")
×
## **References**
References filter input
×
### HTML and CSS
[HTML Tags Reference](https://www.w3schools.com/tags/default.asp "HTML Tag Reference")
[CSS Reference](https://www.w3schools.com/cssref/default.asp "CSS Reference")
[W3.CSS Reference](https://www.w3schools.com/w3css/w3css_references.asp "W3.CSS Reference")
[Bootstrap 3 Reference](https://www.w3schools.com/bootstrap/bootstrap_ref_all_classes.asp "Bootstrap3 Reference")
[Bootstrap 4 Reference](https://www.w3schools.com/bootstrap4/bootstrap_ref_all_classes.asp "Bootstrap4 Reference")
[Color Names](https://www.w3schools.com/colors/colors_names.asp "Color Names")
[Icons Reference](https://www.w3schools.com/icons/default.asp "Icons Reference")
[SVG Reference](https://www.w3schools.com/graphics/svg_reference.asp "SVG Reference")
[Canvas Reference](https://www.w3schools.com/graphics/canvas_reference.asp "Canvas Reference")
[Sass Reference](https://www.w3schools.com/sass/sass_functions_string.php "SASS Reference")
[UTF-8 Charset Reference](https://www.w3schools.com/charsets/default.asp "UTF-8 Reference")
[UTF-8 Emojis Reference](https://www.w3schools.com/charsets/ref_emoji_smileys.asp "UTF-8 Emojis Reference")
### JavaScript
[JavaScript Reference](https://www.w3schools.com/jsref/default.asp "JavaScript Reference")
[HTML DOM Reference](https://www.w3schools.com/jsref/dom_obj_document.asp "HTML DOM Reference")
[jQuery Reference](https://www.w3schools.com/jquery/jquery_ref_overview.asp "jQuery Reference")
[Vue Reference](https://www.w3schools.com/vue/vue_ref_builtin-attributes.php "Vue Reference")
[Angular Reference](https://www.w3schools.com/angular/angularjs_ref_directives.asp "Angular Reference")
[JSON Reference](https://www.w3schools.com/jsref/jsref_obj_json.asp "JSON Reference")
[AppML Reference](https://www.w3schools.com/appml/appml_reference.asp "AppML Reference")
[W3.JS Reference](https://www.w3schools.com/e3js/w3js_references.asp "W3.JS Reference")
### Backend
[Python Reference](https://www.w3schools.com/python/python_reference.asp "Python Reference")
[SQL Reference](https://www.w3schools.com/sql/sql_ref_keywords.asp "SQL Reference")
[MySQL Reference](https://www.w3schools.com/mysql/mysql_datatypes.asp "MySQL Reference")
[PHP Reference](https://www.w3schools.com/php/php_ref_overview.asp "PHP Reference")
[Java Reference](https://www.w3schools.com/java/java_ref_reference.asp "Java Reference")
[C Reference](https://www.w3schools.com/c/c_ref_reference.php "C Reference")
[C++ Reference](https://www.w3schools.com/cpp/cpp_ref_reference.asp "C++ Reference")
[Django Reference](https://www.w3schools.com/django/django_ref_template_tags.php "Django Reference")
[ASP Reference](https://www.w3schools.com/asp/asp_ref_vbscript_functions.asp "ASP Reference")
[Node.js Reference](https://www.w3schools.com/nodejs/ref_modules.asp "Node.js Reference")
[XML Reference](https://www.w3schools.com/xml/dom_nodetype.asp "XML Reference")
×
## **Exercises**
Excercises filter input
×
### HTML and CSS
[HTML](https://www.w3schools.com/html/html_exercises.asp "HTML Exercises") [Exercise](https://www.w3schools.com/html/html_exercises.asp "HTML Exercises") [Quiz](https://www.w3schools.com/html/html_quiz.asp "HTML Quizzes") [Challenge](https://www.w3schools.com/html/html_challenges.asp "HTML Code Challenges")
[CSS](https://www.w3schools.com/css/css_exercises.asp "CSS Exercises") [Exercise](https://www.w3schools.com/css/css_exercises.asp "CSS Exercises") [Quiz](https://www.w3schools.com/css/css_quiz.asp "CSS Quizzes") [Challenge](https://www.w3schools.com/css/css_challenges.asp "CSS Code Challenges")
[Bootstrap 3](https://www.w3schools.com/bootstrap/bootstrap_exercises.asp "Bootstrap 3 Exercises") [Exercise](https://www.w3schools.com/bootstrap/bootstrap_exercises.asp "Bootstrap 3 Exercises") [Quiz](https://www.w3schools.com/bootstrap/bootstrap_quiz.asp "Bootstrap 3 Quizzes")
[Bootstrap 4](https://www.w3schools.com/bootstrap4/bootstrap_exercises.asp "Bootstrap 4 Exercises") [Exercise](https://www.w3schools.com/bootstrap4/bootstrap_exercises.asp "Bootstrap 4 Exercises") [Quiz](https://www.w3schools.com/bootstrap4/bootstrap_quiz.asp "Bootstrap 4 Quizzes")
[Bootstrap 5](https://www.w3schools.com/bootstrap5/bootstrap_exercises.php "Bootstrap 5 Exercises") [Exercise](https://www.w3schools.com/bootstrap5/bootstrap_exercises.php "Bootstrap 5 Exercises") [Quiz](https://www.w3schools.com/bootstrap5/bootstrap_quiz.php "Bootstrap 5 Quizzes")
### Data Analytics
[DSA](https://www.w3schools.com/dsa/dsa_exercises.php "DSA Exercises") [Exercise](https://www.w3schools.com/dsa/dsa_exercises.php "DSA Exercises") [Quiz](https://www.w3schools.com/dsa/dsa_quiz.php "DSA Quizzes")
[NumPy](https://www.w3schools.com/python/numpy/numpy_exercises.asp "NumPy Exercises") [Exercise](https://www.w3schools.com/python/numpy/numpy_exercises.asp "NumPy Exercises") [Quiz](https://www.w3schools.com/python/numpy/numpy_quiz.asp "NumPy Quizzes")
[Pandas](https://www.w3schools.com/python/pandas/pandas_exercises.asp "Pandas Exercises") [Exercise](https://www.w3schools.com/python/pandas/pandas_exercises.asp "Pandas Exercises") [Quiz](https://www.w3schools.com/python/pandas/pandas_quiz.asp "Pandas Quizzes")
[SciPy](https://www.w3schools.com/python/scipy/scipy_exercises.php "SciPy Exercises") [Exercise](https://www.w3schools.com/python/scipy/scipy_exercises.php "SciPy Exercises") [Quiz](https://www.w3schools.com/python/scipy/scipy_quiz.php "SciPy Quizzes")
[Excel](https://www.w3schools.com/excel/excel_exercises.php "Excel Exercises") [Exercise](https://www.w3schools.com/excel/excel_exercises.php "Excel Exercises")
[What is an Exercise?](https://www.w3schools.com/exercises/index.php "W3Schools Exercises") [What is a Quiz?](https://www.w3schools.com/quiztest/default.asp "W3Schools Quizzes") [What is a Challenge?](https://www.w3schools.com/challenges/index.php "W3Schools Challenges")
### JavaScript
[JavaScript](https://www.w3schools.com/js/js_exercises.asp "JavaScript Exercises") [Exercise](https://www.w3schools.com/js/js_exercises.asp "JavaScript Exercises") [Quiz](https://www.w3schools.com/js/js_quiz.asp "JavaScript Quizzes")
[React](https://www.w3schools.com/react/react_exercises.asp "React Exercises") [Exercise](https://www.w3schools.com/react/react_exercises.asp "React Exercises") [Quiz](https://www.w3schools.com/react/react_quiz.asp "React Quizzes")
[jQuery](https://www.w3schools.com/jquery/jquery_exercises.asp "jQuery Exercises") [Exercise](https://www.w3schools.com/jquery/jquery_exercises.asp "jQuery Exercises") [Quiz](https://www.w3schools.com/jquery/jquery_quiz.asp "jQuery Quizzes")
[Vue](https://www.w3schools.com/vue/vue_exercises.php "Vue Exercises") [Exercise](https://www.w3schools.com/vue/vue_exercises.php "Vue Exercises") [Quiz](https://www.w3schools.com/vue/vue_quiz.php "Vue Quizzes")
[Angular](https://www.w3schools.com/angular/angular_exercises.asp "Angular Exercises") [Exercise](https://www.w3schools.com/angular/angular_exercises.asp "Angular Exercises") [Quiz](https://www.w3schools.com/angular/angular_quiz.asp "Angular Quizzes")
### Backend
[Python](https://www.w3schools.com/python/python_exercises.asp "Python Exercises") [Exercise](https://www.w3schools.com/python/python_exercises.asp "Python Exercises") [Quiz](https://www.w3schools.com/python/python_quiz.asp "Python Quizzes") [Challenge](https://www.w3schools.com/python/python_challenges.asp "Python Code Challenges")
[SQL](https://www.w3schools.com/sql/sql_exercises.asp "SQL Exercises") [Exercise](https://www.w3schools.com/sql/sql_exercises.asp "SQL Exercises") [Quiz](https://www.w3schools.com/sql/sql_quiz.asp "SQL Quizzes")
[MySQL](https://www.w3schools.com/mysql/mysql_exercises.asp "MySQL Exercises") [Exercise](https://www.w3schools.com/mysql/mysql_exercises.asp "MySQL Exercises") [Quiz](https://www.w3schools.com/mysql/mysql_quiz.asp "MySQL Quizzes")
[PHP](https://www.w3schools.com/php/php_exercises.asp "PHP Exercises") [Exercise](https://www.w3schools.com/php/php_exercises.asp "PHP Exercises") [Quiz](https://www.w3schools.com/php/php_quiz.asp "PHP Quizzes")
[Java](https://www.w3schools.com/java/java_exercises.asp "Java Exercises") [Exercise](https://www.w3schools.com/java/java_exercises.asp "Java Exercises") [Quiz](https://www.w3schools.com/java/java_quiz.asp "Java Quizzes") [Challenge](https://www.w3schools.com/java/java_challenges.asp "Java Code Challenges")
[C](https://www.w3schools.com/c/c_exercises.php "C Exercises") [Exercise](https://www.w3schools.com/c/c_exercises.php "C Exercises") [Quiz](https://www.w3schools.com/c/c_quiz.php "C Quizzes") [Challenge](https://www.w3schools.com/c/c_challenges.php "C Challenges")
[C++](https://www.w3schools.com/cpp/cpp_exercises.asp "C++ Exercises") [Exercise](https://www.w3schools.com/cpp/cpp_exercises.asp "C++ Exercises") [Quiz](https://www.w3schools.com/cpp/cpp_quiz.asp "C++ Quizzes") [Challenge](https://www.w3schools.com/cpp/cpp_challenges.asp "C++ Code Challenges")
[C\#](https://www.w3schools.com/cs/cs_exercises.php "C# Exercises") [Exercise](https://www.w3schools.com/cs/cs_exercises.php "C# Exercises") [Quiz](https://www.w3schools.com/cs/cs_quiz.php "C# Quizzes")
[R](https://www.w3schools.com/r/r_exercises.asp "R Exercises") [Exercise](https://www.w3schools.com/r/r_exercises.asp "R Exercises") [Quiz](https://www.w3schools.com/r/r_quiz.asp "R Quizzes")
[Kotlin](https://www.w3schools.com/kotlin/kotlin_exercises.php "Kotlin Exercises") [Exercise](https://www.w3schools.com/kotlin/kotlin_exercises.php "Kotlin Exercises") [Quiz](https://www.w3schools.com/kotlin/kotlin_quiz.php "Kotlin Quizzes")
[Django](https://www.w3schools.com/django/django_exercises.php "Django Exercises") [Exercise](https://www.w3schools.com/django/django_exercises.php "Django Exercises") [Quiz](https://www.w3schools.com/django/django_quiz.php "Django Quizzes")
[Node.js](https://www.w3schools.com/nodejs/nodejs_exercises.asp "Node.js Exercises") [Exercise](https://www.w3schools.com/nodejs/nodejs_exercises.asp "Node.js Exercises") [Quiz](https://www.w3schools.com/nodejs/nodejs_quiz.asp "Node.js Quizzes")
[PostgreSQL](https://www.w3schools.com/postgresql/postgresql_exercises.php "PostgreSQL Exercises") [Exercise](https://www.w3schools.com/postgresql/postgresql_exercises.php "PostgreSQL Exercises") [Quiz](https://www.w3schools.com/postgresql/postgresql_quiz.php "PostgreSQL Quizzes")
[TypeScript](https://www.w3schools.com/typescript/typescript_exercises.php "TypeScript Exercises") [Exercise](https://www.w3schools.com/typescript/typescript_exercises.php "TypeScript Exercises") [Quiz](https://www.w3schools.com/typescript/typescript_quiz.php "TypeScript Quizzes")
[Git](https://www.w3schools.com/git/git_exercises.asp "Git Exercises") [Exercise](https://www.w3schools.com/git/git_exercises.asp "Git Exercises") [Quiz](https://www.w3schools.com/git/git_quiz.asp "Git Quizzes")
[Bash](https://www.w3schools.com/bash/bash_exercises.php "Bash Exercises") [Exercise](https://www.w3schools.com/bash/bash_exercises.php "Bash Exercises") [Quiz](https://www.w3schools.com/bash/bash_quiz.php "Bash Quizzes")
[Go](https://www.w3schools.com/go/go_exercises.php "Go Exercises") [Exercise](https://www.w3schools.com/go/go_exercises.php "Go Exercises")
[MongoDB](https://www.w3schools.com/mongodb/mongodb_exercises.php "MongoDB Exercises") [Exercise](https://www.w3schools.com/mongodb/mongodb_exercises.php "MongoDB Exercises")
### Data Analytics
[DSA](https://www.w3schools.com/dsa/dsa_exercises.php "DSA Exercises") [Exercise](https://www.w3schools.com/dsa/dsa_exercises.php "DSA Exercises") [Quiz](https://www.w3schools.com/dsa/dsa_quiz.php "DSA Quizzes")
[NumPy](https://www.w3schools.com/python/numpy/numpy_exercises.asp "NumPy Exercises") [Exercise](https://www.w3schools.com/python/numpy/numpy_exercises.asp "NumPy Exercises") [Quiz](https://www.w3schools.com/python/numpy/numpy_quiz.asp "NumPy Quizzes")
[Pandas](https://www.w3schools.com/python/pandas/pandas_exercises.asp "Pandas Exercises") [Exercise](https://www.w3schools.com/python/pandas/pandas_exercises.asp "Pandas Exercises") [Quiz](https://www.w3schools.com/python/pandas/pandas_quiz.asp "Pandas Quizzes")
[SciPy](https://www.w3schools.com/python/scipy/scipy_exercises.php "SciPy Exercises") [Exercise](https://www.w3schools.com/python/scipy/scipy_exercises.php "SciPy Exercises") [Quiz](https://www.w3schools.com/python/scipy/scipy_quiz.php "SciPy Quizzes")
[Excel](https://www.w3schools.com/excel/excel_exercises.php "Excel Exercises") [Exercise](https://www.w3schools.com/excel/excel_exercises.php "Excel Exercises")
[What is an Exercise?](https://www.w3schools.com/exercises/index.php "W3Schools Exercises") [What is a Quiz?](https://www.w3schools.com/quiztest/default.asp "W3Schools Quizzes") [What is a Code Challenge?](https://www.w3schools.com/challenges/index.php "W3Schools Code Challenges")
×
## **Certificates**
Filter field for certifications
×
### HTML and CSS
[HTML](https://campus.w3schools.com/collections/certifications/products/html-certificate "HTML Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/html-certificate "HTML Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/html-course "Paid HTML Course") [Bootcamp](https://www.w3schools.com/bootcamp/html-css.php "HTML Bootcamp")
[CSS](https://campus.w3schools.com/collections/certifications/products/css-certificate "CSS Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/css-certificate "CSS Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/css-course "Paid CSS Course") [Bootcamp](https://www.w3schools.com/bootcamp/html-css.php "CSS Bootcamp")
[Bootstrap 3](https://campus.w3schools.com/collections/certifications/products/bootstrap-3-certificate "Bootstrap 3 Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/bootstrap-3-certificate "Bootstrap 3 Certification Exam") [Course](https://campus.w3schools.com/collections/single-courses/products/bootstrap-course "Paid Bootstrap 3 Course")
[Bootstrap 4](https://campus.w3schools.com/collections/certifications/products/bootstrap-4-certificate "Bootstrap 4 Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/bootstrap-4-certificate "Bootstrap 4 Certification Exam") [Course](https://campus.w3schools.com/collections/single-courses/products/bootstrap-4-course "Paid Bootstrap 4 Course")
[Bootstrap 5](https://campus.w3schools.com/collections/certifications/products/bootstrap-5-certificate "Bootstrap 5 Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/bootstrap-5-certificate "Bootstrap 5 Certification Exam")
### Data Analytics
[DSA](https://campus.w3schools.com/products/dsa-certification-exam "DSA Certificate Exam") [Certificate](https://campus.w3schools.com/products/dsa-certification-exam "DSA Certificate Exam")
[Data Analytics](https://campus.w3schools.com/products/data-analytics-program "Paid Data Analytics Course") [Course](https://campus.w3schools.com/products/data-analytics-program "Paid Data Analytics Course")
[NumPy](https://campus.w3schools.com/products/numpy-certification-exam "NumPy Certification Exam") [Certificate](https://campus.w3schools.com/products/numpy-certification-exam "NumPy Certification Exam") [Course](https://campus.w3schools.com/products/numpy-course "Paid NumPy Course")
[Pandas](https://campus.w3schools.com/products/pandas-certification-exam "Pandas Certification Exam") [Certificate](https://campus.w3schools.com/products/pandas-certification-exam "Pandas Certification Exam") [Course](https://campus.w3schools.com/products/pandas-course "Paid Pandas Course")
[Excel](https://campus.w3schools.com/products/excel-certificate "Excel Certification Exam") [Certificate](https://campus.w3schools.com/products/excel-certificate "Excel Certification Exam")
[Social Media](https://campus.w3schools.com/collections/course-best-sellers/products/social-media-marketing-course "Paid Social Media Course") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/social-media-marketing-course "Paid Social Media Course")
[What is a Certificate?](https://campus.w3schools.com/ "W3Schools Campus")
[What is a Bootcamp?](https://www.w3schools.com/bootcamp/index.php "W3Schools Bootcamps")
### Programs
[Full Access Best Value\!](https://campus.w3schools.com/collections/course-catalog/products/w3schools-full-access-course "Paid Full Access Course")
[Front End](https://campus.w3schools.com/collections/certifications/products/front-end-course "Paid Front End Course") [Certificate](https://campus.w3schools.com/collections/certifications/products/front-end-certificate "Front End Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/front-end-course "Paid Front End Development Course")
[Web Dev.](https://campus.w3schools.com/collections/certifications/products/modern-web-development-certification "Web Development Certification") [Certificate](https://campus.w3schools.com/collections/certifications/products/modern-web-development-certification "Web Development Certification") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/learn-modern-web-development "Paid Web Development Course")
[Web App](https://campus.w3schools.com/collections/certifications/products/web-application-development-certificates "Web Application Development Certification") [Certificate](https://campus.w3schools.com/collections/certifications/products/web-application-development-certificates "Web Application Development Certification") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/web-application-development-course "Paid Web Application Course")
[Web Design](https://campus.w3schools.com/collections/certifications/products/web-design-certification "Web Design Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/web-design-certification "Web Design Certification Exam") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/learn-web-design "Paid Web Design Course")
### JavaScript
[JavaScript](https://campus.w3schools.com/collections/certifications/products/javascript-certificate "JavaScript Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/javascript-certificate "JavaScript Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/javascript-course "Paid JavaScript Course") [Bootcamp](https://www.w3schools.com/bootcamp/javascript.php "JavaScript Bootcamp")
[React](https://campus.w3schools.com/collections/certifications/products/react-js-certificate "React.js Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/react-js-certificate "React.js Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/react-js-course "Paid React.js Course") [Bootcamp](https://www.w3schools.com/bootcamp/react.php "React Bootcamp")
[jQuery](https://campus.w3schools.com/collections/certifications/products/jquery-certificate "jQuery Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/jquery-certificate "jQuery Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/jquery-course "Paid jQuery Course")
[Vue](https://campus.w3schools.com/products/vue-js-certification-exam "Vue Certification Exam") [Certificate](https://campus.w3schools.com/products/vue-js-certification-exam "Vue Certification Exam")
### Programs
[Full Access Best Value\!](https://campus.w3schools.com/collections/course-catalog/products/w3schools-full-access-course "Paid Full Access Course")
[Front End](https://campus.w3schools.com/collections/certifications/products/front-end-certificate "Front End Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/front-end-certificate "Front End Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/front-end-course "Paid Front End Development Course") [Bootcamp](https://www.w3schools.com/bootcamp/web-development.php "Front End Development Bootcamp")
[Web Dev.](https://campus.w3schools.com/collections/certifications/products/modern-web-development-certification "Web Development Certification") [Certificate](https://campus.w3schools.com/collections/certifications/products/modern-web-development-certification "Web Development Certification") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/learn-modern-web-development "Paid Web Development Course") [Bootcamp](https://www.w3schools.com/bootcamp/web-development.php "Web Development Bootcamp")
[Web App](https://campus.w3schools.com/collections/certifications/products/web-application-development-certificates "Web Application Development Certification") [Certificate](https://campus.w3schools.com/collections/certifications/products/web-application-development-certificates "Web Application Development Certification") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/web-application-development-course "Paid Web Application Course")
[Web Design](https://campus.w3schools.com/collections/certifications/products/web-design-certification "Web Design Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/web-design-certification "Web Design Certification Exam") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/learn-web-design "Paid Web Design Course")
### Programs
[Full Access Best Value\!](https://campus.w3schools.com/collections/course-catalog/products/w3schools-full-access-course "Paid Full Access Course")
[Front End](https://campus.w3schools.com/collections/certifications/products/front-end-certificate "Front End Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/front-end-certificate "Front End Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/front-end-course "Paid Front End Development Course") [Bootcamp](https://www.w3schools.com/bootcamp/web-development.php "Front End Development Bootcamp")
[Web Dev.](https://campus.w3schools.com/collections/certifications/products/modern-web-development-certification "Web Development Certification") [Certificate](https://campus.w3schools.com/collections/certifications/products/modern-web-development-certification "Web Development Certification") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/learn-modern-web-development "Paid Web Development Course") [Bootcamp](https://www.w3schools.com/bootcamp/web-development.php "Web Development Bootcamp")
[Web App](https://campus.w3schools.com/collections/certifications/products/web-application-development-certificates "Web Application Development Certification") [Certificate](https://campus.w3schools.com/collections/certifications/products/web-application-development-certificates "Web Application Development Certification") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/web-application-development-course "Paid Web Application Course")
[Web Design](https://campus.w3schools.com/collections/certifications/products/web-design-certification "Web Design Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/web-design-certification "Web Design Certification Exam") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/learn-web-design "Paid Web Design Course")
### Backend
[Python](https://campus.w3schools.com/collections/certifications/products/python-certificate "Python Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/python-certificate "Python Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/python-course "Paid Python Course") [Bootcamp](https://www.w3schools.com/bootcamp/python.php "Python Bootcamp")
[SQL](https://campus.w3schools.com/collections/certifications/products/sql-certificate "SQL Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/sql-certificate "SQL Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/sql-course "SQL Python Course") [Bootcamp](https://www.w3schools.com/bootcamp/sql.php "SQL Bootcamp")
[MySQL](https://campus.w3schools.com/collections/certifications/products/mysql-certificate "MySQL Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/mysql-certificate "MySQL Certification Exam")
[PHP](https://campus.w3schools.com/collections/certifications/products/php-certificate "PHP Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/php-certificate "PHP Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/php-course "Paid PHP Course")
[Java](https://campus.w3schools.com/collections/certifications/products/java-certificate "Java Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/java-certificate "Java Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/java-course "Paid Java Course")
[C](https://campus.w3schools.com/products/c-certification-exam "C Certification Exam") [Certificate](https://campus.w3schools.com/products/c-certification-exam "C Certification Exam")
[C++](https://campus.w3schools.com/collections/certifications/products/c-certificate "C++ Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/c-certificate "C++ Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/c-course-1 "Paid C++ Course")
[C\#](https://campus.w3schools.com/collections/certifications/products/c-certificate-1 "C# Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/c-certificate-1 "C# Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/c-course "Paid C# Course")
[R](https://campus.w3schools.com/collections/course-catalog/products/r-course "Paid R Course") [Course](https://campus.w3schools.com/collections/course-catalog/products/r-course "Paid R Course")
[Django](https://campus.w3schools.com/products/django-certification-exam "Django Certification Exam") [Certificate](https://campus.w3schools.com/products/django-certification-exam "Django Certification Exam")
[NodeJS](https://campus.w3schools.com/products/nodejs-certificate "NodeJS Certification Exam") [Certificate](https://campus.w3schools.com/products/nodejs-certificate "NodeJS Certification Exam") [Bootcamp](https://www.w3schools.com/bootcamp/nodejs.php "NodeJS Bootcamp")
[TypeScript](https://campus.w3schools.com/collections/certifications/products/typescript-certificate "TypeScript Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/typescript-certificate "TypeScript Certification Exam") [Course](https://campus.w3schools.com/products/learn-typescript "Paid TypeScript Course")
[XML](https://campus.w3schools.com/collections/certifications/products/xml-certificate "XML Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/xml-certificate "XML Certification Exam") [Course](https://campus.w3schools.com/collections/course-catalog/products/xml-course "Paid XML Course")
[Cyber Security](https://campus.w3schools.com/collections/certifications/products/cyber-security-certificate "Cyber Security Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/cyber-security-certificate "Cyber Security Certification Exam") [Course](https://campus.w3schools.com/products/cyber-security-course "Paid Cyber Security Course")
[Accessibility](https://campus.w3schools.com/collections/certifications/products/accessibility-certificate "Accessibility Certification Exam") [Certificate](https://campus.w3schools.com/collections/certifications/products/accessibility-certificate "Accessibility Certification Exam") [Course](https://campus.w3schools.com/products/accessibility-course "Paid Accessibility Course")
### Data Analytics
[DSA](https://campus.w3schools.com/products/dsa-certification-exam "DSA Certification Exam") [Exam](https://campus.w3schools.com/products/dsa-certification-exam "DSA Certification Exam")
[Data Analytics](https://campus.w3schools.com/products/data-analytics-program "Paid Data Analytics Course") [Course](https://campus.w3schools.com/products/data-analytics-program "Paid Data Analytics Course")
[NumPy](https://campus.w3schools.com/products/numpy-course "Paid NumPy Course") [Course](https://campus.w3schools.com/products/numpy-course "Paid NumPy Course")
[Pandas](https://campus.w3schools.com/products/pandas-course "Paid SciPy Course") [Course](https://campus.w3schools.com/products/pandas-course "Paid SciPy Course")
[Excel](https://campus.w3schools.com/products/excel-certificate "Excel Certification Exam") [Certificate](https://campus.w3schools.com/products/excel-certificate "Excel Certification Exam")
[Social Media](https://campus.w3schools.com/collections/course-best-sellers/products/social-media-marketing-course "Paid Social Media Course") [Course](https://campus.w3schools.com/collections/course-best-sellers/products/social-media-marketing-course "Paid Social Media Course")
[What is a Certificate?](https://campus.w3schools.com/ "W3Schools Campus")
×
## **All Our Services**
Dark mode
Services filter input
×
W3Schools offers a wide range of services and products for beginners and professionals,
helping millions of people everyday to learn and master new skills.
[Free Tutorials Enjoy our free tutorials like millions of other internet users since 1999](https://www.w3schools.com/tutorials/index.php "Tutorials")
[References Explore our selection of references covering all popular coding languages](https://www.w3schools.com/references/index.php "References")
[Create a Website Create your own website with **W3Schools Spaces** - no setup required](https://www.w3schools.com/spaces/index.php "Create a Website")
[Exercises Test your skills with different exercises](https://www.w3schools.com/exercises/index.php "Test yourself with exercises")
[Quizzes Test yourself with multiple choice questions](https://www.w3schools.com/quiztest/default.asp "Test yourself with quizzes")
[Code Challenges Test your skills with interactive code challenges](https://www.w3schools.com/challenges/index.php "Test yourself with Code Challenges")
[Get Certified Document your knowledge](https://campus.w3schools.com/collections/certifications "Certificates")
[Log in / Sign Up Create an account to track your progress](https://profile.w3schools.com/sign-up?redirect_url=https%3A%2F%2Fwww.w3schools.com%2Fdsa%2Fdsa_algo_graphs_dijkstra.php "Log in our Sign up")
[League Earn XP and climb the ranks with different challenges](https://www.w3schools.com/league/ "Earn XP and climb the ranks with our League")
[Upgrade Become a PLUS user and unlock powerful features (ad-free, hosting, support,..)](https://order.w3schools.com/plans "Upgrade subscription")
[Where To Start Not sure where you want to start? Follow our guided path](https://www.w3schools.com/where_to_start.asp "Where To Start")
[Code Editor (Try it) With our online code editor, you can edit code and view the result in your browser](https://www.w3schools.com/tryit/default.asp "W3Schools Code Editor")
[Bootcamps Learn from passionate instructors through live online sessions](https://www.w3schools.com/bootcamp/index.php "W3Schools Bootcamps")
[Templates We have created a bunch of responsive website templates you can use - for free\!](https://www.w3schools.com/w3css/w3css_templates.asp "Free Web Templates")
[Web Hosting Host your own website, and share it to the world with **W3Schools Spaces**](https://www.w3schools.com/spaces/index.php "Web Hosting with Spaces")
[Create a Server Create your own server using Python, PHP, React.js, Node.js, Java, C\#, etc.](https://www.w3schools.com/spaces/index.php "Get your own server")
[How To's Large collection of code snippets for HTML, CSS and JavaScript](https://www.w3schools.com/howto/default.asp "How To Collection")
[CSS Framework Build fast and responsive sites using our free **W3.CSS** framework](https://www.w3schools.com/w3css/default.asp "W3.CSS Framework")
[Videos Learn the basics of HTML in a fun and engaging video tutorial](https://www.w3schools.com/videos/index.php "HTML Video Tutorial")
[Browser Statistics Read long term trends of browser usage](https://www.w3schools.com/browsers/default.asp "Browser Statistics")
[Typing Speed Test your typing speed](https://www.w3schools.com/typingspeed/default.asp "Test Your Typing speed")
[Color Picker Use our color picker to find different RGB, HEX and HSL colors. ](https://www.w3schools.com/colors/colors_picker.asp "Color Picker")
[Newsletter Join our newsletter and get access to exclusive content every month](https://campus.w3schools.com/pages/newsletter "Join Our Newsletter")
[Emojis Reference Check out our refererence page with all the emojis supported in HTML 😊](https://www.w3schools.com/charsets/ref_emoji_intro.asp "Emojis Reference")
[Code Game W3Schools Coding Game! Help the lynx collect pine cones ](https://www.w3schools.com/codegame/index.html "Coding Game")
[UTF-8 Reference Check out our full UTF-8 Character reference](https://www.w3schools.com/charsets/default.asp "UTF-8 Reference")
[Community Chat, Learn and Connect with Us on Discord](https://discord.com/invite/w3schools "W3Schools Community")
[Teachers Contact us about W3Schools Academy for educational institutions](https://www.w3schools.com/academy/index.php "W3Schools Academy / Classroom")
[For Businesses Contact us about W3Schools Academy for your organization](https://www.w3schools.com/academy/index.php "W3Schools Academy / Classroom")
#### Contact Us
About sales: sales@w3schools.com
About errors: help@w3schools.com
[Web Developer Tools Free online tools to help with your everyday development tasks](https://www.w3schools.com/tools/index.php "Web Developer Tools")
[**](https://www.linkedin.com/company/w3schools.com/ "W3Schools on LinkedIn") [**](https://discord.com/invite/w3schools "Join the W3schools community on Discord") [**](https://www.facebook.com/w3schoolscom/ "W3Schools on Facebook") [**](https://www.instagram.com/w3schools.com_official/ "W3Schools on Instagram")
×
❮
❯
[HTML](https://www.w3schools.com/html/default.asp "HTML Tutorial") [CSS](https://www.w3schools.com/css/default.asp "CSS Tutorial") [JAVASCRIPT](https://www.w3schools.com/js/default.asp "JavaScript Tutorial") [SQL](https://www.w3schools.com/sql/default.asp "SQL Tutorial") [PYTHON](https://www.w3schools.com/python/default.asp "Python Tutorial") [JAVA](https://www.w3schools.com/java/default.asp "Java Tutorial") [PHP](https://www.w3schools.com/php/default.asp "PHP Tutorial") [HOW TO](https://www.w3schools.com/howto/default.asp "How to") [W3.CSS](https://www.w3schools.com/w3css/default.asp "W3.CSS Tutorial") [C](https://www.w3schools.com/c/index.php "C Tutorial") [C++](https://www.w3schools.com/cpp/default.asp "C++ Tutorial") [C\#](https://www.w3schools.com/cs/index.php "C# Tutorial") [BOOTSTRAP](https://www.w3schools.com/bootstrap/bootstrap_ver.asp "Bootstrap Tutorial") [REACT](https://www.w3schools.com/react/default.asp "React Tutorial") [MYSQL](https://www.w3schools.com/mysql/default.asp "MySQL Tutorial") [JQUERY](https://www.w3schools.com/jquery/default.asp "JQuery Tutorial") [EXCEL](https://www.w3schools.com/excel/index.php "Excel Tutorial") [XML](https://www.w3schools.com/xml/default.asp "XML Tutorial") [DJANGO](https://www.w3schools.com/django/index.php "Django Tutorial") [NUMPY](https://www.w3schools.com/python/numpy/default.asp "NumPy Tutorial") [PANDAS](https://www.w3schools.com/python/pandas/default.asp "Pandas Tutorial") [NODEJS](https://www.w3schools.com/nodejs/default.asp "Node.js Tutorial") [DSA](https://www.w3schools.com/dsa/index.php "DSA Tutorial") [TYPESCRIPT](https://www.w3schools.com/typescript/index.php "TypeScript Tutorial") [SWIFT](https://www.w3schools.com/swift/default.asp "Swift Tutorial") [ANGULAR](https://www.w3schools.com/angular/default.asp "Angular Tutorial") [ANGULARJS](https://www.w3schools.com/angularjs/default.asp "Angular.js Tutorial") [GIT](https://www.w3schools.com/git/default.asp "Git Tutorial") [POSTGRESQL](https://www.w3schools.com/postgresql/index.php "PostgreSQL Tutorial") [MONGODB](https://www.w3schools.com/mongodb/index.php "MongoDB Tutorial") [ASP](https://www.w3schools.com/asp/default.asp "ASP Tutorial") [AI](https://www.w3schools.com/ai/default.asp "A.I. Tutorial") [R](https://www.w3schools.com/r/default.asp "R Tutorial") [GO](https://www.w3schools.com/go/index.php "Go Tutorial") [KOTLIN](https://www.w3schools.com/kotlin/index.php "Kotlin Tutorial") [SWIFT](https://www.w3schools.com/swift/default.asp "Swift Tutorial") [SASS](https://www.w3schools.com/sass/default.asp "Sass Tutorial") [VUE](https://www.w3schools.com/vue/index.php "Vue.js Tutorial") [GEN AI](https://www.w3schools.com/gen_ai/index.php "Gen A.I. Tutorial") [SCIPY](https://www.w3schools.com/python/scipy/index.php "SciPy Tutorial") [AWS](https://www.w3schools.com/aws/index.php "AWS Tutorial") [CYBERSECURITY](https://www.w3schools.com/cybersecurity/index.php "Cyber security Tutorial") [DATA SCIENCE](https://www.w3schools.com/datascience/default.asp "Data science Tutorial") [INTRO TO PROGRAMMING](https://www.w3schools.com/programming/index.php "Introduction to Programming") [HTML & CSS](https://www.w3schools.com/htmlcss/default.asp "Introduction to HTML & CSS") [BASH](https://www.w3schools.com/bash/index.php "Bash Tutorial") [RUST](https://www.w3schools.com/rust/index.php "Rust Tutorial") [TOOLS](https://www.w3schools.com/tools/index.php "Web Developer Tools")
## DSA Tutorial
[DSA HOME](https://www.w3schools.com/dsa/index.php) [DSA Intro](https://www.w3schools.com/dsa/dsa_intro.php) [DSA Simple Algorithm](https://www.w3schools.com/dsa/dsa_algo_simple.php)
## Arrays
[DSA Arrays](https://www.w3schools.com/dsa/dsa_data_arrays.php) [DSA Bubble Sort](https://www.w3schools.com/dsa/dsa_algo_bubblesort.php) [DSA Selection Sort](https://www.w3schools.com/dsa/dsa_algo_selectionsort.php) [DSA Insertion Sort](https://www.w3schools.com/dsa/dsa_algo_insertionsort.php) [DSA Quick Sort](https://www.w3schools.com/dsa/dsa_algo_quicksort.php) [DSA Counting Sort](https://www.w3schools.com/dsa/dsa_algo_countingsort.php) [DSA Radix Sort](https://www.w3schools.com/dsa/dsa_algo_radixsort.php) [DSA Merge Sort](https://www.w3schools.com/dsa/dsa_algo_mergesort.php) [DSA Linear Search](https://www.w3schools.com/dsa/dsa_algo_linearsearch.php) [DSA Binary Search](https://www.w3schools.com/dsa/dsa_algo_binarysearch.php)
## Linked Lists
[DSA Linked Lists](https://www.w3schools.com/dsa/dsa_theory_linkedlists.php) [DSA Linked Lists in Memory](https://www.w3schools.com/dsa/dsa_theory_linkedlists_memory.php) [DSA Linked Lists Types](https://www.w3schools.com/dsa/dsa_data_linkedlists_types.php) [Linked Lists Operations](https://www.w3schools.com/dsa/dsa_algo_linkedlists_operations.php)
## Stacks & Queues
[DSA Stacks](https://www.w3schools.com/dsa/dsa_data_stacks.php) [DSA Queues](https://www.w3schools.com/dsa/dsa_data_queues.php)
## Hash Tables
[DSA Hash Tables](https://www.w3schools.com/dsa/dsa_theory_hashtables.php) [DSA Hash Sets](https://www.w3schools.com/dsa/dsa_data_hashsets.php) [DSA Hash Maps](https://www.w3schools.com/dsa/dsa_data_hashmaps.php)
## Trees
[DSA Trees](https://www.w3schools.com/dsa/dsa_theory_trees.php) [DSA Binary Trees](https://www.w3schools.com/dsa/dsa_data_binarytrees.php) [DSA Pre-order Traversal](https://www.w3schools.com/dsa/dsa_algo_binarytrees_preorder.php) [DSA In-order Traversal](https://www.w3schools.com/dsa/dsa_algo_binarytrees_inorder.php) [DSA Post-order Traversal](https://www.w3schools.com/dsa/dsa_algo_binarytrees_postorder.php) [DSA Array Implementation](https://www.w3schools.com/dsa/dsa_data_binarytrees_arrayImpl.php) [DSA Binary Search Trees](https://www.w3schools.com/dsa/dsa_data_binarysearchtrees.php) [DSA AVL Trees](https://www.w3schools.com/dsa/dsa_data_avltrees.php)
## Graphs
[DSA Graphs](https://www.w3schools.com/dsa/dsa_theory_graphs.php) [Graphs Implementation](https://www.w3schools.com/dsa/dsa_data_graphs_implementation.php) [DSA Graphs Traversal](https://www.w3schools.com/dsa/dsa_algo_graphs_traversal.php) [DSA Cycle Detection](https://www.w3schools.com/dsa/dsa_algo_graphs_cycledetection.php)
## Shortest Path
[DSA Shortest Path](https://www.w3schools.com/dsa/dsa_theory_graphs_shortestpath.php) [DSA Dijkstra's](https://www.w3schools.com/dsa/dsa_algo_graphs_dijkstra.php) [DSA Bellman-Ford](https://www.w3schools.com/dsa/dsa_algo_graphs_bellmanford.php)
## Minimum Spanning Tree
[Minimum Spanning Tree](https://www.w3schools.com/dsa/dsa_theory_mst_minspantree.php) [DSA Prim's](https://www.w3schools.com/dsa/dsa_algo_mst_prim.php) [DSA Kruskal's](https://www.w3schools.com/dsa/dsa_algo_mst_kruskal.php)
## Maximum Flow
[DSA Maximum Flow](https://www.w3schools.com/dsa/dsa_theory_graphs_maxflow.php) [DSA Ford-Fulkerson](https://www.w3schools.com/dsa/dsa_algo_graphs_fordfulkerson.php) [DSA Edmonds-Karp](https://www.w3schools.com/dsa/dsa_algo_graphs_edmondskarp.php)
## Time Complexity
[Introduction](https://www.w3schools.com/dsa/dsa_timecomplexity_theory.php) [Bubble Sort](https://www.w3schools.com/dsa/dsa_timecomplexity_bblsort.php) [Selection Sort](https://www.w3schools.com/dsa/dsa_timecomplexity_selsort.php) [Insertion Sort](https://www.w3schools.com/dsa/dsa_timecomplexity_insertionsort.php) [Quick Sort](https://www.w3schools.com/dsa/dsa_timecomplexity_quicksort.php) [Counting Sort](https://www.w3schools.com/dsa/dsa_timecomplexity_countsort.php) [Radix Sort](https://www.w3schools.com/dsa/dsa_timecomplexity_radixsort.php) [Merge Sort](https://www.w3schools.com/dsa/dsa_timecomplexity_mergesort.php) [Linear Search](https://www.w3schools.com/dsa/dsa_timecomplexity_linearsearch.php) [Binary Search](https://www.w3schools.com/dsa/dsa_timecomplexity_binarysearch.php)
## DSA Reference
[DSA Euclidean Algorithm](https://www.w3schools.com/dsa/dsa_ref_euclidean_algorithm.php) [DSA Huffman Coding](https://www.w3schools.com/dsa/dsa_ref_huffman_coding.php) [DSA The Traveling Salesman](https://www.w3schools.com/dsa/dsa_ref_traveling_salesman.php) [DSA 0/1 Knapsack](https://www.w3schools.com/dsa/dsa_ref_knapsack.php) [DSA Memoization](https://www.w3schools.com/dsa/dsa_ref_memoization.php) [DSA Tabulation](https://www.w3schools.com/dsa/dsa_ref_tabulation.php) [DSA Dynamic Programming](https://www.w3schools.com/dsa/dsa_ref_dynamic_programming.php) [DSA Greedy Algorithms](https://www.w3schools.com/dsa/dsa_ref_greedy.php)
## DSA Examples
[DSA Examples](https://www.w3schools.com/dsa/dsa_examples.php) [DSA Exercises](https://www.w3schools.com/dsa/dsa_exercises.php) [DSA Quiz](https://www.w3schools.com/dsa/dsa_quiz.php) [DSA Syllabus](https://www.w3schools.com/dsa/dsa_syllabus.php) [DSA Study Plan](https://www.w3schools.com/dsa/dsa_study_plan.php) [DSA Certificate](https://www.w3schools.com/dsa/dsa_exam.php)
# DSA Dijkstra's Algorithm
[❮ Previous](https://www.w3schools.com/dsa/dsa_theory_graphs_shortestpath.php) [Next ❯](https://www.w3schools.com/dsa/dsa_algo_graphs_bellmanford.php)
Dijkstra's shortest path algorithm was invented in 1956 by the Dutch computer scientist Edsger W. Dijkstra during a twenty minutes coffee break, while out shopping with his fiancée in Amsterdam.
The reason for inventing the algorithm was to test a new computer called ARMAC.
## Dijkstra's Algorithm
Dijkstra's algorithm finds the shortest path from one vertex to all other vertices.
It does so by repeatedly selecting the nearest unvisited vertex and calculating the distance to all the unvisited neighboring vertices.
Run Dijkstra's
Dijkstra's algorithm is often considered to be the most straightforward algorithm for solving the shortest path problem.
Dijkstra's algorithm is used for solving single-source shortest path problems for directed or undirected paths. Single-source means that one vertex is chosen to be the start, and the algorithm will find the shortest path from that vertex to all other vertices.
Dijkstra's algorithm does not work for graphs with negative edges. For graphs with negative edges, the Bellman-Ford algorithm that is described on the next page, can be used instead.
To find the shortest path, Dijkstra's algorithm needs to know which vertex is the source, it needs a way to mark vertices as visited, and it needs an overview of the current shortest distance to each vertex as it works its way through the graph, updating these distances when a shorter distance is found.
**How it works:**
1. Set initial distances for all vertices: 0 for the source vertex, and infinity for all the other.
2. Choose the unvisited vertex with the shortest distance from the start to be the current vertex. So the algorithm will always start with the source as the current vertex.
3. For each of the current vertex's unvisited neighbor vertices, calculate the distance from the source and update the distance if the new, calculated, distance is lower.
4. We are now done with the current vertex, so we mark it as visited. A visited vertex is not checked again.
5. Go back to step 2 to choose a new current vertex, and keep repeating these steps until all vertices are visited.
6. In the end we are left with the shortest path from the source vertex to every other vertex in the graph.
In the animation above, when a vertex is marked as visited, the vertex and its edges become faded to indicate that Dijkstra's algorithm is now done with that vertex, and will not visit it again.
**Note:** This basic version of Dijkstra's algorithm gives us the value of the shortest path cost to every vertex, but not what the actual path is. So for example, in the animation above, we get the shortest path cost value 10 to vertex F, but the algorithm does not give us which vertices (D-\>E-\>C-\>D-\>F) that make up this shortest path. We will add this functionality further down here on this page.
***
[REMOVE ADS](https://order.w3schools.com/plans)
***
## A Detailed Dijkstra Simulation
Run the simulation below to get a more detailed understanding of how Dijkstra's algorithm runs on a specific graph, finding the shortest distances from vertex D.
inf
F
2
5
5
3
inf
B
inf
C
5
5
2
2
inf
A
4
4
4
inf
E
0
D
inf
G
2
2
5
5
4
4
2
2
6
6
8
2
Play
Reset
This simulation shows how distances are calculated from vertex D to all other vertices, by always choosing the next vertex to be the closest unvisited vertex from the starting point.
Follow the step-by-step description below to get all the details of how Dijkstra's algorithm calculates the shortest distances.
***
## Manual Run Through
Consider the Graph below.
F
2
5
3
4
5
2
B
C
5
5
2
A
4
4
E
D
G
We want to find the shortest path from the source vertex D to all other vertices, so that for example the shortest path to C is D-\>E-\>C, with path weight 2+4=6.
To find the shortest path, Dijkstra's algorithm uses an array with the distances to all other vertices, and initially sets these distances to infinite, or a very big number. And the distance to the vertex we start from (the source) is set to 0.
```
distances = [inf, inf, inf, 0, inf, inf, inf]
#vertices [ A , B , C , D, E , F , G ]
```
The image below shows the initial infinite distances to other vertices from the starting vertex D. The distance value for vertex D is 0 because that is the starting point.
inf
F
2
5
3
4
5
2
inf
B
inf
C
5
5
2
inf
A
4
4
inf
E
0
D
inf
G
Dijkstra's algorithm then sets vertex D as the current vertex, and looks at the distance to the adjacent vertices. Since the initial distance to vertices A and E is infinite, the new distance to these are updated with the edge weights. So vertex A gets the distance changed from inf to 4, and vertex E gets the distance changed to 2. As mentioned on the previous page, updating the distance values in this way is called 'relaxing'.
inf
F
2
5
3
4
5
2
inf
B
inf
C
5
5
2
4
A
4
4
2
E
0
D
inf
G
After relaxing vertices A and E, vertex D is considered visited, and will not be visited again.
The next vertex to be chosen as the current vertex must the vertex with the shortest distance to the source vertex (vertex D), among the previously unvisited vertices. Vertex E is therefore chosen as the current vertex after vertex D.
inf
F
2
5
3
4
5
2
inf
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
The distance to all adjacent and not previously visited vertices from vertex E must now be calculated, and updated if needed.
The calculated distance from D to vertex A, via E, is 2+4=6. But the current distance to vertex A is already 4, which is lower, so the distance to vertex A is not updated.
The distance to vertex C is calculated to be 2+4=6, which is less than infinity, so the distance to vertex C is updated.
Similarly, the distance to node G is calculated and updated to be 2+5=7.
The next vertex to be visited is vertex A because it has the shortest distance from D of all the unvisited vertices.
inf
F
2
5
3
4
5
2
inf
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
The calculated distance to vertex C, via A, is 4+3=7, which is higher than the already set distance to vertex C, so the distance to vertex C is not updated.
Vertex A is now marked as visited, and the next current vertex is vertex C because that has the lowest distance from vertex D between the remaining unvisited vertices.
11
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
Vertex F gets updated distance 6+5=11, and vertex B gets updated distance 6+2=8.
Calculated distance to vertex G via vertex C is 6+5=11 which is higher than the already set distance of 7, so distance to vertex G is not updated.
Vertex C is marked as visited, and the next vertex to be visited is G because is has the lowest distance between the remaining unvisited vertices.
11
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
Vertex F already has a distance of 11. This is lower than the calculated distance from G, which is 7+5=12, so the distance to vertex F is not updated.
Vertex G is marked as visited, and B becomes the current vertex because it has the lowest distance of the remaining unvisited vertices.
10
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
The new distance to F via B is 8+2=10, because it is lower than F's existing distance of 11.
Vertex B is marked as visited, and there is nothing to check for the last unvisited vertex F, so Dijkstra's algorithm is finished.
Every vertex has been visited only once, and the result is the lowest distance from the source vertex D to every other vertex in the graph.
***
## Implementation of Dijkstra's Algorithm
To implement Dijkstra's algorithm, we create a `Graph` class. The `Graph` represents the graph with its vertices and edges:
```
```
**Line 3:** We create the `adj_matrix` to hold all the edges and edge weights. Initial values are set to `0`.
**Line 4:** `size` is the number of vertices in the graph.
**Line 5:** The `vertex_data` holds the names of all the vertices.
**Line 7-10:** The `add_edge` method is used to add an edge from vertex `u` to vertex `v`, with edge weight `weight`.
**Line 12-14:** The `add_vertex_data` method is used to add a vertex to the graph. The index where the vertex should belong is given with the `vertex` argument, and `data` is the name of the vertex.
The `Graph` class also contains the method that runs Dijkstra's algorithm:
```
```
**Line 18-19:** The initial distance is set to infinity for all vertices in the `distances` array, except for the start vertex, where the distance is 0.
**Line 20:** All vertices are initially set to `False` to mark them as not visited in the `visited` array.
**Line 23-28:** The next current vertex is found. Outgoing edges from this vertex will be checked to see if shorter distances can be found. It is the unvisited vertex with the lowest distance from the start.
**Line 30-31:** If the next current vertex has not been found, the algorithm is finished. This means that all vertices that are reachable from the source have been visited.
**Line 33:** The current vertex is set as visited before relaxing adjacent vertices. This is more effective because we avoid checking the distance to the current vertex itself.
**Line 35-39:** Distances are calculated for not visited adjacent vertices, and updated if the new calculated distance is lower.
After defining the `Graph` class, the vertices and edges must be defined to initialize the specific graph, and the complete code for this Dijkstra's algorithm example looks like this:
### Example
Python:
```
class Graph:
def __init__(self, size):
self.adj_matrix = [[0] * size for _ in range(size)]
self.size = size
self.vertex_data = [''] * size
def add_edge(self, u, v, weight):
if 0 <= u < self.size and 0 <= v < self.size:
self.adj_matrix[u][v] = weight
self.adj_matrix[v][u] = weight # For undirected graph
def add_vertex_data(self, vertex, data):
if 0 <= vertex < self.size:
self.vertex_data[vertex] = data
def dijkstra(self, start_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
distances = [float('inf')] * self.size
distances[start_vertex] = 0
visited = [False] * self.size
for _ in range(self.size):
min_distance = float('inf')
u = None
for i in range(self.size):
if not visited[i] and distances[i] < min_distance:
min_distance = distances[i]
u = i
if u is None:
break
visited[u] = True
for v in range(self.size):
if self.adj_matrix[u][v] != 0 and not visited[v]:
alt = distances[u] + self.adj_matrix[u][v]
if alt < distances[v]:
distances[v] = alt
return distances
g = Graph(7)
g.add_vertex_data(0, 'A')
g.add_vertex_data(1, 'B')
g.add_vertex_data(2, 'C')
g.add_vertex_data(3, 'D')
g.add_vertex_data(4, 'E')
g.add_vertex_data(5, 'F')
g.add_vertex_data(6, 'G')
g.add_edge(3, 0, 4) # D - A, weight 5
g.add_edge(3, 4, 2) # D - E, weight 2
g.add_edge(0, 2, 3) # A - C, weight 3
g.add_edge(0, 4, 4) # A - E, weight 4
g.add_edge(4, 2, 4) # E - C, weight 4
g.add_edge(4, 6, 5) # E - G, weight 5
g.add_edge(2, 5, 5) # C - F, weight 5
g.add_edge(2, 1, 2) # C - B, weight 2
g.add_edge(1, 5, 2) # B - F, weight 2
g.add_edge(6, 5, 5) # G - F, weight 5
# Dijkstra's algorithm from D to all vertices
print("\nDijkstra's Algorithm starting from vertex D:")
distances = g.dijkstra('D')
for i, d in enumerate(distances):
print(f"Distance from D to {g.vertex_data[i]}: {d}")
```
[Try it Yourself »](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_dijkstra)
***
## Dijkstra's Algorithm on Directed Graphs
To run Dijkstra's algorithm on directed graphs, very few changes are needed.
Similarly to the change we needed for [cycle detection for directed graphs](https://www.w3schools.com/dsa/dsa_algo_graphs_cycledetection.php#directed), we just need to remove one line of code so that the adjacency matrix is not symmetric anymore.
Let's implement this directed graph and run Dijkstra's algorithm from vertex D.
inf
F
2
5
3
4
5
2
inf
B
inf
C
5
5
2
inf
A
4
4
inf
E
0
D
inf
G
Here is the implementation of Dijkstra's algorithm on the directed graph, with D as the source vertex:
### Example
Python:
```
```
[Try it Yourself »](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_dijkstra_directed)
The image below shows us the shortest distances from vertex D as calculated by Dijkstra's algorithm.
11
F
2
5
3
4
5
2
inf
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
This result is similar to the previous example using Dijkstra's algorithm on the undirected graph. However, there's a key difference: in this case, vertex B cannot be visited from D, and this means that the shortest distance from D to F is now 11, not 10, because the path can no longer go through vertex B.
***
## Returning The Paths from Dijkstra's Algorithm
With a few adjustments, the actual shortest paths can also be returned by Dijkstra's algorithm, in addition to the shortest path values. So for example, instead of just returning that the shortest path value is 10 from vertex D to F, the algorithm can also return that the shortest path is "D-\>E-\>C-\>B-\>F".
10
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
To return the path, we create a `predecessors` array to keep the previous vertex in the shortest path for each vertex. The `predecessors` array can be used to backtrack to find the shortest path for every vertex.
### Example
Python:
```
```
[Try it Yourself »](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_dijkstra_path)
**Line 7 and 29:** The `predecessors` array is first initialized with `None` values, then it is updated with the correct predecessor for each vertex as the shortest path values are updated.
**Line 33-42:** The `get_path` method uses the `predecessors` array and returns a string with the shortest path from start to end vertex.
***
## Dijkstra's Algorithm with a Single Destination Vertex
Let's say we are only interested in finding the shortest path between two vertices, like finding the shortest distance between vertex D and vertex F in the graph below.
inf
F
2
5
3
4
5
2
inf
B
inf
C
5
5
2
inf
A
4
4
inf
E
0
D
inf
G
5
inf
H
4
inf
I
2
inf
J
Dijkstra's algorithm is normally used for finding the shortest path from one source vertex to all other vertices in the graph, but it can also be modified to only find the shortest path from the source to a single destination vertex, by just stopping the algorithm when the destination is reached (visited).
This means that for the specific graph in the image above, Dijkstra's algorithm will stop after visiting F (the destination vertex), before visiting vertices H, I and J because they are farther away from D than F is.
Below we can see the status of the calculated distances when Dijkstra's algorithm has found the shortest distance from D to F, and stops running.
10
F
2
5
3
4
5
2
8
B
6
C
5
5
2
4
A
4
4
2
E
0
D
7
G
5
12
H
4
11
I
2
inf
J
In the image above, vertex F has just got updated with distance 10 from vertex B. Since F is the unvisited vertex with the lowest distance from D, it would normally be the next current vertex, but since it is the destination, the algorithm stops. If the algorithm did not stop, J would be the next vertex to get an updated distance 11+2=13, from vertex I.
The code below is Dijkstra's algorithm implemented to find the shortest path to a single destination vertex:
### Example
Python:
```
```
[Try it Yourself »](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_dijkstra_singledestination)
**Line 20-23:** If we are about to choose the destination vertex as the current vertex and mark it as visited, it means we have already calculated the shortest distance to the destination vertex, and Dijkstra's algorithm can be stopped in this single destination case.
***
## Time Complexity for Dijkstra's Algorithm
With V V as the number of vertices in our graph, the time complexity for Dijkstra's algorithm is
O(V2) O ( V 2 )
The reason why we get this time complexity is that the vertex with the lowest distance must to be search for to choose the next current vertex, and that takes O(V) O ( V ) time. And since this must to be done for every vertex connected to the source, we need to factor that in, and so we get time complexity O(V2) O ( V 2 ) for Dijkstra's algorithm.
By using a Min-heap or Fibonacci-heap data structure for the distances instead (not yet explained in this tutorial), the time needed to search for the minimum distance vertex is reduced from O(V) O ( V ) to O(logV) O ( log V ), which results in an improved time complexity for Dijkstra's algorithm
O(V⋅logV\+E) O ( V ⋅ log V \+ E )
Where V V is the number of vertices in the graph, and E E is the number of edges.
The improvement we get from using a Min-heap data structure for Dijkstra's algorithm is especially good if we have a large and sparse graph, which means a graph with a large number of vertices, but not as many edges.
The implementation of Dijkstra's algorithm with the Fibonacci-heap data structure is better for dense graphs, where each vertex has an edge to almost every other vertex.
***
## DSA Exercises
***
[❮ Previous](https://www.w3schools.com/dsa/dsa_algo_graphs_cycledetection.php) [Next ❯](https://www.w3schools.com/dsa/dsa_algo_graphs_bellmanford.php)
[★ +1](https://profile.w3schools.com/log-in?redirect_url=https%3A%2F%2Fwww.w3schools.com%2Fdsa%2Fdsa_algo_graphs_dijkstra.php "Your W3Schools Profile")
[Sign in to track progress](https://profile.w3schools.com/log-in?redirect_url=https%3A%2F%2Fpathfinder.w3schools.com&origin=https%3A%2F%2Fwww.w3schools.com%2Fdsa%2Fdsa_algo_graphs_dijkstra.php "Sign in to track your progress")
[](https://www.w3schools.com/academy/index.php)
#### [COLOR PICKER](https://www.w3schools.com/colors/colors_picker.asp)
[](https://www.w3schools.com/colors/colors_picker.asp)
[REMOVE ADS](https://order.w3schools.com/plans)
***
[PLUS](https://order.w3schools.com/plans "Become a PLUS user and unlock powerful features")
[SPACES](https://www.w3schools.com/spaces/index.php "Get your own website with W3Schools Spaces")
[GET CERTIFIED](https://campus.w3schools.com/collections/certifications "Document your knowledge by getting certified")
[FOR TEACHERS](https://www.w3schools.com/academy/index.php "Contact us about W3Schools Academy for educational institutions")
[BOOTCAMPS](https://www.w3schools.com/bootcamp/index.php "W3Schools Bootcamps")
[CONTACT US]("Contact us about sales or errors")
×
## Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com
## Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com
##### Top Tutorials
[HTML Tutorial](https://www.w3schools.com/html/default.asp)
[CSS Tutorial](https://www.w3schools.com/css/default.asp)
[JavaScript Tutorial](https://www.w3schools.com/js/default.asp)
[How To Tutorial](https://www.w3schools.com/howto/default.asp)
[SQL Tutorial](https://www.w3schools.com/sql/default.asp)
[Python Tutorial](https://www.w3schools.com/python/default.asp)
[W3.CSS Tutorial](https://www.w3schools.com/w3css/default.asp)
[Bootstrap Tutorial](https://www.w3schools.com/bootstrap/bootstrap_ver.asp)
[PHP Tutorial](https://www.w3schools.com/php/default.asp)
[Java Tutorial](https://www.w3schools.com/java/default.asp)
[C++ Tutorial](https://www.w3schools.com/cpp/default.asp)
[jQuery Tutorial](https://www.w3schools.com/jquery/default.asp)
##### Top References
[HTML Reference](https://www.w3schools.com/tags/default.asp)
[CSS Reference](https://www.w3schools.com/cssref/index.php)
[JavaScript Reference](https://www.w3schools.com/jsref/default.asp)
[SQL Reference](https://www.w3schools.com/sql/sql_ref_keywords.asp)
[Python Reference](https://www.w3schools.com/python/python_reference.asp)
[W3.CSS Reference](https://www.w3schools.com/w3css/w3css_references.asp)
[Bootstrap Reference](https://www.w3schools.com/bootstrap/bootstrap_ref_all_classes.asp)
[PHP Reference](https://www.w3schools.com/php/php_ref_overview.asp)
[HTML Colors](https://www.w3schools.com/colors/colors_names.asp)
[Java Reference](https://www.w3schools.com/java/java_ref_keywords.asp)
[AngularJS Reference](https://www.w3schools.com/angularjs/angularjs_ref_directives.asp)
[jQuery Reference](https://www.w3schools.com/jquery/jquery_ref_overview.asp)
##### Top Examples
[HTML Examples](https://www.w3schools.com/html/html_examples.asp)
[CSS Examples](https://www.w3schools.com/css/css_examples.asp)
[JavaScript Examples](https://www.w3schools.com/js/js_examples.asp)
[How To Examples](https://www.w3schools.com/howto/default.asp)
[SQL Examples](https://www.w3schools.com/sql/sql_examples.asp)
[Python Examples](https://www.w3schools.com/python/python_examples.asp)
[W3.CSS Examples](https://www.w3schools.com/w3css/w3css_examples.asp)
[Bootstrap Examples](https://www.w3schools.com/bootstrap/bootstrap_examples.asp)
[PHP Examples](https://www.w3schools.com/php/php_examples.asp)
[Java Examples](https://www.w3schools.com/java/java_examples.asp)
[XML Examples](https://www.w3schools.com/xml/xml_examples.asp)
[jQuery Examples](https://www.w3schools.com/jquery/jquery_examples.asp)
[Get Certified](https://campus.w3schools.com/collections/course-catalog)
[HTML Certificate](https://campus.w3schools.com/collections/certifications/products/html-certificate)
[CSS Certificate](https://campus.w3schools.com/collections/certifications/products/css-certificate)
[JavaScript Certificate](https://campus.w3schools.com/collections/certifications/products/javascript-certificate)
[Front End Certificate](https://campus.w3schools.com/collections/certifications/products/front-end-certificate)
[SQL Certificate](https://campus.w3schools.com/collections/certifications/products/sql-certificate)
[Python Certificate](https://campus.w3schools.com/collections/certifications/products/python-certificate)
[PHP Certificate](https://campus.w3schools.com/collections/certifications/products/php-certificate)
[jQuery Certificate](https://campus.w3schools.com/collections/certifications/products/jquery-certificate)
[Java Certificate](https://campus.w3schools.com/collections/certifications/products/java-certificate)
[C++ Certificate](https://campus.w3schools.com/collections/certifications/products/c-certificate)
[C\# Certificate](https://campus.w3schools.com/collections/certifications/products/c-certificate-1)
[XML Certificate](https://campus.w3schools.com/collections/certifications/products/xml-certificate)
[**](https://www.linkedin.com/company/w3schools.com/ "W3Schools on LinkedIn") [**](https://discord.com/invite/w3schools "Join the W3schools community on Discord") [**](https://www.facebook.com/w3schoolscom/ "W3Schools on Facebook") [**](https://www.instagram.com/w3schools.com_official/ "W3Schools on Instagram")
[FORUM](https://www.w3schools.com/forum/index.php "Forum") [ABOUT](https://www.w3schools.com/about/default.asp "About W3Schools") [ACADEMY](https://www.w3schools.com/academy/index.php "Contact us about W3Schools Academy for educational institutions and organizations")
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our [terms of use](https://www.w3schools.com/about/about_copyright.asp), [cookies]() and [privacy policy](https://www.w3schools.com/about/about_privacy.asp).
[Copyright 1999-2026](https://www.w3schools.com/about/about_copyright.asp) by Refsnes Data. All Rights Reserved. [W3Schools is Powered by W3.CSS](https://www.w3schools.com/w3css/default.asp). |
| Readable Markdown | ## DSA Dijkstra's Algorithm
Dijkstra's shortest path algorithm was invented in 1956 by the Dutch computer scientist Edsger W. Dijkstra during a twenty minutes coffee break, while out shopping with his fiancée in Amsterdam.
The reason for inventing the algorithm was to test a new computer called ARMAC.
## Dijkstra's Algorithm
Dijkstra's algorithm finds the shortest path from one vertex to all other vertices.
It does so by repeatedly selecting the nearest unvisited vertex and calculating the distance to all the unvisited neighboring vertices.
Dijkstra's algorithm is often considered to be the most straightforward algorithm for solving the shortest path problem.
Dijkstra's algorithm is used for solving single-source shortest path problems for directed or undirected paths. Single-source means that one vertex is chosen to be the start, and the algorithm will find the shortest path from that vertex to all other vertices.
Dijkstra's algorithm does not work for graphs with negative edges. For graphs with negative edges, the Bellman-Ford algorithm that is described on the next page, can be used instead.
To find the shortest path, Dijkstra's algorithm needs to know which vertex is the source, it needs a way to mark vertices as visited, and it needs an overview of the current shortest distance to each vertex as it works its way through the graph, updating these distances when a shorter distance is found.
**How it works:**
1. Set initial distances for all vertices: 0 for the source vertex, and infinity for all the other.
2. Choose the unvisited vertex with the shortest distance from the start to be the current vertex. So the algorithm will always start with the source as the current vertex.
3. For each of the current vertex's unvisited neighbor vertices, calculate the distance from the source and update the distance if the new, calculated, distance is lower.
4. We are now done with the current vertex, so we mark it as visited. A visited vertex is not checked again.
5. Go back to step 2 to choose a new current vertex, and keep repeating these steps until all vertices are visited.
6. In the end we are left with the shortest path from the source vertex to every other vertex in the graph.
In the animation above, when a vertex is marked as visited, the vertex and its edges become faded to indicate that Dijkstra's algorithm is now done with that vertex, and will not visit it again.
**Note:** This basic version of Dijkstra's algorithm gives us the value of the shortest path cost to every vertex, but not what the actual path is. So for example, in the animation above, we get the shortest path cost value 10 to vertex F, but the algorithm does not give us which vertices (D-\>E-\>C-\>D-\>F) that make up this shortest path. We will add this functionality further down here on this page.
***
***
## A Detailed Dijkstra Simulation
Run the simulation below to get a more detailed understanding of how Dijkstra's algorithm runs on a specific graph, finding the shortest distances from vertex D.
This simulation shows how distances are calculated from vertex D to all other vertices, by always choosing the next vertex to be the closest unvisited vertex from the starting point.
Follow the step-by-step description below to get all the details of how Dijkstra's algorithm calculates the shortest distances.
***
## Manual Run Through
Consider the Graph below.
F 2 5 3 4 5 2 B C 5 5 2 A 4 4 E D G
We want to find the shortest path from the source vertex D to all other vertices, so that for example the shortest path to C is D-\>E-\>C, with path weight 2+4=6.
To find the shortest path, Dijkstra's algorithm uses an array with the distances to all other vertices, and initially sets these distances to infinite, or a very big number. And the distance to the vertex we start from (the source) is set to 0.
```
distances = [inf, inf, inf, 0, inf, inf, inf]
#vertices [ A , B , C , D, E , F , G ]
```
The image below shows the initial infinite distances to other vertices from the starting vertex D. The distance value for vertex D is 0 because that is the starting point.
inf F 2 5 3 4 5 2 inf B inf C 5 5 2 inf A 4 4 inf E 0 D inf G
Dijkstra's algorithm then sets vertex D as the current vertex, and looks at the distance to the adjacent vertices. Since the initial distance to vertices A and E is infinite, the new distance to these are updated with the edge weights. So vertex A gets the distance changed from inf to 4, and vertex E gets the distance changed to 2. As mentioned on the previous page, updating the distance values in this way is called 'relaxing'.
inf F 2 5 3 4 5 2 inf B inf C 5 5 2 4 A 4 4 2 E 0 D inf G
After relaxing vertices A and E, vertex D is considered visited, and will not be visited again.
The next vertex to be chosen as the current vertex must the vertex with the shortest distance to the source vertex (vertex D), among the previously unvisited vertices. Vertex E is therefore chosen as the current vertex after vertex D.
inf F 2 5 3 4 5 2 inf B 6 C 5 5 2 4 A 4 4 2 E 0 D 7 G
The distance to all adjacent and not previously visited vertices from vertex E must now be calculated, and updated if needed.
The calculated distance from D to vertex A, via E, is 2+4=6. But the current distance to vertex A is already 4, which is lower, so the distance to vertex A is not updated.
The distance to vertex C is calculated to be 2+4=6, which is less than infinity, so the distance to vertex C is updated.
Similarly, the distance to node G is calculated and updated to be 2+5=7.
The next vertex to be visited is vertex A because it has the shortest distance from D of all the unvisited vertices.
inf F 2 5 3 4 5 2 inf B 6 C 5 5 2 4 A 4 4 2 E 0 D 7 G
The calculated distance to vertex C, via A, is 4+3=7, which is higher than the already set distance to vertex C, so the distance to vertex C is not updated.
Vertex A is now marked as visited, and the next current vertex is vertex C because that has the lowest distance from vertex D between the remaining unvisited vertices.
11 F 2 5 3 4 5 2 8 B 6 C 5 5 2 4 A 4 4 2 E 0 D 7 G
Vertex F gets updated distance 6+5=11, and vertex B gets updated distance 6+2=8.
Calculated distance to vertex G via vertex C is 6+5=11 which is higher than the already set distance of 7, so distance to vertex G is not updated.
Vertex C is marked as visited, and the next vertex to be visited is G because is has the lowest distance between the remaining unvisited vertices.
11 F 2 5 3 4 5 2 8 B 6 C 5 5 2 4 A 4 4 2 E 0 D 7 G
Vertex F already has a distance of 11. This is lower than the calculated distance from G, which is 7+5=12, so the distance to vertex F is not updated.
Vertex G is marked as visited, and B becomes the current vertex because it has the lowest distance of the remaining unvisited vertices.
10 F 2 5 3 4 5 2 8 B 6 C 5 5 2 4 A 4 4 2 E 0 D 7 G
The new distance to F via B is 8+2=10, because it is lower than F's existing distance of 11.
Vertex B is marked as visited, and there is nothing to check for the last unvisited vertex F, so Dijkstra's algorithm is finished.
Every vertex has been visited only once, and the result is the lowest distance from the source vertex D to every other vertex in the graph.
***
## Implementation of Dijkstra's Algorithm
To implement Dijkstra's algorithm, we create a `Graph` class. The `Graph` represents the graph with its vertices and edges:
```
class Graph:
def __init__(self, size):
self.adj_matrix = [[0] * size for _ in range(size)]
self.size = size
self.vertex_data = [''] * size
def add_edge(self, u, v, weight):
if 0 <= u < self.size and 0 <= v < self.size:
self.adj_matrix[u][v] = weight
self.adj_matrix[v][u] = weight # For undirected graph
def add_vertex_data(self, vertex, data):
if 0 <= vertex < self.size:
self.vertex_data[vertex] = data
```
**Line 3:** We create the `adj_matrix` to hold all the edges and edge weights. Initial values are set to `0`.
**Line 4:** `size` is the number of vertices in the graph.
**Line 5:** The `vertex_data` holds the names of all the vertices.
**Line 7-10:** The `add_edge` method is used to add an edge from vertex `u` to vertex `v`, with edge weight `weight`.
**Line 12-14:** The `add_vertex_data` method is used to add a vertex to the graph. The index where the vertex should belong is given with the `vertex` argument, and `data` is the name of the vertex.
The `Graph` class also contains the method that runs Dijkstra's algorithm:
```
def dijkstra(self, start_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
distances = [float('inf')] * self.size
distances[start_vertex] = 0
visited = [False] * self.size
for _ in range(self.size):
min_distance = float('inf')
u = None
for i in range(self.size):
if not visited[i] and distances[i] < min_distance:
min_distance = distances[i]
u = i
if u is None:
break
visited[u] = True
for v in range(self.size):
if self.adj_matrix[u][v] != 0 and not visited[v]:
alt = distances[u] + self.adj_matrix[u][v]
if alt < distances[v]:
distances[v] = alt
return distances
```
**Line 18-19:** The initial distance is set to infinity for all vertices in the `distances` array, except for the start vertex, where the distance is 0.
**Line 20:** All vertices are initially set to `False` to mark them as not visited in the `visited` array.
**Line 23-28:** The next current vertex is found. Outgoing edges from this vertex will be checked to see if shorter distances can be found. It is the unvisited vertex with the lowest distance from the start.
**Line 30-31:** If the next current vertex has not been found, the algorithm is finished. This means that all vertices that are reachable from the source have been visited.
**Line 33:** The current vertex is set as visited before relaxing adjacent vertices. This is more effective because we avoid checking the distance to the current vertex itself.
**Line 35-39:** Distances are calculated for not visited adjacent vertices, and updated if the new calculated distance is lower.
After defining the `Graph` class, the vertices and edges must be defined to initialize the specific graph, and the complete code for this Dijkstra's algorithm example looks like this:
### Example
Python:
```
class Graph:
def __init__(self, size):
self.adj_matrix = [[0] * size for _ in range(size)]
self.size = size
self.vertex_data = [''] * size
def add_edge(self, u, v, weight):
if 0 <= u < self.size and 0 <= v < self.size:
self.adj_matrix[u][v] = weight
self.adj_matrix[v][u] = weight # For undirected graph
def add_vertex_data(self, vertex, data):
if 0 <= vertex < self.size:
self.vertex_data[vertex] = data
def dijkstra(self, start_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
distances = [float('inf')] * self.size
distances[start_vertex] = 0
visited = [False] * self.size
for _ in range(self.size):
min_distance = float('inf')
u = None
for i in range(self.size):
if not visited[i] and distances[i] < min_distance:
min_distance = distances[i]
u = i
if u is None:
break
visited[u] = True
for v in range(self.size):
if self.adj_matrix[u][v] != 0 and not visited[v]:
alt = distances[u] + self.adj_matrix[u][v]
if alt < distances[v]:
distances[v] = alt
return distances
g = Graph(7)
g.add_vertex_data(0, 'A')
g.add_vertex_data(1, 'B')
g.add_vertex_data(2, 'C')
g.add_vertex_data(3, 'D')
g.add_vertex_data(4, 'E')
g.add_vertex_data(5, 'F')
g.add_vertex_data(6, 'G')
g.add_edge(3, 0, 4) # D - A, weight 5
g.add_edge(3, 4, 2) # D - E, weight 2
g.add_edge(0, 2, 3) # A - C, weight 3
g.add_edge(0, 4, 4) # A - E, weight 4
g.add_edge(4, 2, 4) # E - C, weight 4
g.add_edge(4, 6, 5) # E - G, weight 5
g.add_edge(2, 5, 5) # C - F, weight 5
g.add_edge(2, 1, 2) # C - B, weight 2
g.add_edge(1, 5, 2) # B - F, weight 2
g.add_edge(6, 5, 5) # G - F, weight 5
# Dijkstra's algorithm from D to all vertices
print("\nDijkstra's Algorithm starting from vertex D:")
distances = g.dijkstra('D')
for i, d in enumerate(distances):
print(f"Distance from D to {g.vertex_data[i]}: {d}")
```
[Try it Yourself »](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_dijkstra)
***
## Dijkstra's Algorithm on Directed Graphs
To run Dijkstra's algorithm on directed graphs, very few changes are needed.
Similarly to the change we needed for [cycle detection for directed graphs](https://www.w3schools.com/dsa/dsa_algo_graphs_cycledetection.php#directed), we just need to remove one line of code so that the adjacency matrix is not symmetric anymore.
Let's implement this directed graph and run Dijkstra's algorithm from vertex D.
inf F 2 5 3 4 5 2 inf B inf C 5 5 2 inf A 4 4 inf E 0 D inf G
Here is the implementation of Dijkstra's algorithm on the directed graph, with D as the source vertex:
### Example
Python:
```
class Graph:
def __init__(self, size):
self.adj_matrix = [[0] * size for _ in range(size)]
self.size = size
self.vertex_data = [''] * size
def add_edge(self, u, v, weight):
if 0 <= u < self.size and 0 <= v < self.size:
self.adj_matrix[u][v] = weight
#self.adj_matrix[v][u] = weight For undirected graph
def add_vertex_data(self, vertex, data):
if 0 <= vertex < self.size:
self.vertex_data[vertex] = data
def dijkstra(self, start_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
distances = [float('inf')] * self.size
distances[start_vertex] = 0
visited = [False] * self.size
for _ in range(self.size):
min_distance = float('inf')
u = None
for i in range(self.size):
if not visited[i] and distances[i] < min_distance:
min_distance = distances[i]
u = i
if u is None:
break
visited[u] = True
for v in range(self.size):
if self.adj_matrix[u][v] != 0 and not visited[v]:
alt = distances[u] + self.adj_matrix[u][v]
if alt < distances[v]:
distances[v] = alt
return distances
g = Graph(7)
g.add_vertex_data(0, 'A')
g.add_vertex_data(1, 'B')
g.add_vertex_data(2, 'C')
g.add_vertex_data(3, 'D')
g.add_vertex_data(4, 'E')
g.add_vertex_data(5, 'F')
g.add_vertex_data(6, 'G')
g.add_edge(3, 0, 4) # D -> A, weight 5
g.add_edge(3, 4, 2) # D -> E, weight 2
g.add_edge(0, 2, 3) # A -> C, weight 3
g.add_edge(0, 4, 4) # A -> E, weight 4
g.add_edge(4, 2, 4) # E -> C, weight 4
g.add_edge(4, 6, 5) # E -> G, weight 5
g.add_edge(2, 5, 5) # C -> F, weight 5
g.add_edge(1, 2, 2) # B -> C, weight 2
g.add_edge(1, 5, 2) # B -> F, weight 2
g.add_edge(6, 5, 5) # G -> F, weight 5
# Dijkstra's algorithm from D to all vertices
print("Dijkstra's Algorithm starting from vertex D:\n")
distances = g.dijkstra('D')
for i, d in enumerate(distances):
print(f"Shortest distance from D to {g.vertex_data[i]}: {d}")
```
[Try it Yourself »](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_dijkstra_directed)
The image below shows us the shortest distances from vertex D as calculated by Dijkstra's algorithm.
11 F 2 5 3 4 5 2 inf B 6 C 5 5 2 4 A 4 4 2 E 0 D 7 G
This result is similar to the previous example using Dijkstra's algorithm on the undirected graph. However, there's a key difference: in this case, vertex B cannot be visited from D, and this means that the shortest distance from D to F is now 11, not 10, because the path can no longer go through vertex B.
***
## Returning The Paths from Dijkstra's Algorithm
With a few adjustments, the actual shortest paths can also be returned by Dijkstra's algorithm, in addition to the shortest path values. So for example, instead of just returning that the shortest path value is 10 from vertex D to F, the algorithm can also return that the shortest path is "D-\>E-\>C-\>B-\>F".
10 F 2 5 3 4 5 2 8 B 6 C 5 5 2 4 A 4 4 2 E 0 D 7 G
To return the path, we create a `predecessors` array to keep the previous vertex in the shortest path for each vertex. The `predecessors` array can be used to backtrack to find the shortest path for every vertex.
### Example
Python:
```
class Graph:
# ... (rest of the Graph class)
def dijkstra(self, start_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
distances = [float('inf')] * self.size
predecessors = [None] * self.size
distances[start_vertex] = 0
visited = [False] * self.size
for _ in range(self.size):
min_distance = float('inf')
u = None
for i in range(self.size):
if not visited[i] and distances[i] < min_distance:
min_distance = distances[i]
u = i
if u is None:
break
visited[u] = True
for v in range(self.size):
if self.adj_matrix[u][v] != 0 and not visited[v]:
alt = distances[u] + self.adj_matrix[u][v]
if alt < distances[v]:
distances[v] = alt
predecessors[v] = u
return distances, predecessors
def get_path(self, predecessors, start_vertex, end_vertex):
path = []
current = self.vertex_data.index(end_vertex)
while current is not None:
path.insert(0, self.vertex_data[current])
current = predecessors[current]
if current == self.vertex_data.index(start_vertex):
path.insert(0, start_vertex)
break
return '->'.join(path) # Join the vertices with '->'
g = Graph(7)
# ... (rest of the graph setup)
# Dijkstra's algorithm from D to all vertices
print("Dijkstra's Algorithm starting from vertex D:\n")
distances, predecessors = g.dijkstra('D')
for i, d in enumerate(distances):
path = g.get_path(predecessors, 'D', g.vertex_data[i])
print(f"{path}, Distance: {d}")
```
[Try it Yourself »](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_dijkstra_path)
**Line 7 and 29:** The `predecessors` array is first initialized with `None` values, then it is updated with the correct predecessor for each vertex as the shortest path values are updated.
**Line 33-42:** The `get_path` method uses the `predecessors` array and returns a string with the shortest path from start to end vertex.
***
## Dijkstra's Algorithm with a Single Destination Vertex
Let's say we are only interested in finding the shortest path between two vertices, like finding the shortest distance between vertex D and vertex F in the graph below.
inf F 2 5 3 4 5 2 inf B inf C 5 5 2 inf A 4 4 inf E 0 D inf G 5 inf H 4 inf I 2 inf J
Dijkstra's algorithm is normally used for finding the shortest path from one source vertex to all other vertices in the graph, but it can also be modified to only find the shortest path from the source to a single destination vertex, by just stopping the algorithm when the destination is reached (visited).
This means that for the specific graph in the image above, Dijkstra's algorithm will stop after visiting F (the destination vertex), before visiting vertices H, I and J because they are farther away from D than F is.
Below we can see the status of the calculated distances when Dijkstra's algorithm has found the shortest distance from D to F, and stops running.
10 F 2 5 3 4 5 2 8 B 6 C 5 5 2 4 A 4 4 2 E 0 D 7 G 5 12 H 4 11 I 2 inf J
In the image above, vertex F has just got updated with distance 10 from vertex B. Since F is the unvisited vertex with the lowest distance from D, it would normally be the next current vertex, but since it is the destination, the algorithm stops. If the algorithm did not stop, J would be the next vertex to get an updated distance 11+2=13, from vertex I.
The code below is Dijkstra's algorithm implemented to find the shortest path to a single destination vertex:
### Example
Python:
```
class Graph:
# ... (existing methods)
def dijkstra(self, start_vertex_data, end_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
end_vertex = self.vertex_data.index(end_vertex_data)
distances = [float('inf')] * self.size
predecessors = [None] * self.size
distances[start_vertex] = 0
visited = [False] * self.size
for _ in range(self.size):
min_distance = float('inf')
u = None
for i in range(self.size):
if not visited[i] and distances[i] < min_distance:
min_distance = distances[i]
u = i
if u is None or u == end_vertex:
print(f"Breaking out of loop. Current vertex: {self.vertex_data[u]}")
print(f"Distances: {distances}")
break
visited[u] = True
print(f"Visited vertex: {self.vertex_data[u]}")
for v in range(self.size):
if self.adj_matrix[u][v] != 0 and not visited[v]:
alt = distances[u] + self.adj_matrix[u][v]
if alt < distances[v]:
distances[v] = alt
predecessors[v] = u
return distances[end_vertex], self.get_path(predecessors, start_vertex_data, end_vertex_data)
# Example usage
g = Graph(7)
# ... (rest of the graph setup)
distance, path = g.dijkstra('D', 'F')
print(f"Path: {path}, Distance: {distance}")
```
[Try it Yourself »](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_dijkstra_singledestination)
**Line 20-23:** If we are about to choose the destination vertex as the current vertex and mark it as visited, it means we have already calculated the shortest distance to the destination vertex, and Dijkstra's algorithm can be stopped in this single destination case.
***
## Time Complexity for Dijkstra's Algorithm
With V as the number of vertices in our graph, the time complexity for Dijkstra's algorithm is
O ( V 2 )
The reason why we get this time complexity is that the vertex with the lowest distance must to be search for to choose the next current vertex, and that takes O ( V ) time. And since this must to be done for every vertex connected to the source, we need to factor that in, and so we get time complexity O ( V 2 ) for Dijkstra's algorithm.
By using a Min-heap or Fibonacci-heap data structure for the distances instead (not yet explained in this tutorial), the time needed to search for the minimum distance vertex is reduced from O ( V ) to O ( log V ), which results in an improved time complexity for Dijkstra's algorithm
O ( V ⋅ log V \+ E )
Where V is the number of vertices in the graph, and E is the number of edges.
The improvement we get from using a Min-heap data structure for Dijkstra's algorithm is especially good if we have a large and sparse graph, which means a graph with a large number of vertices, but not as many edges.
The implementation of Dijkstra's algorithm with the Fibonacci-heap data structure is better for dense graphs, where each vertex has an edge to almost every other vertex.
***
## DSA Exercises
*** |
| Shard | 40 (laksa) |
| Root Hash | 10756103332767711440 |
| Unparsed URL | com,w3schools!www,/dsa/dsa_algo_graphs_dijkstra.php s443 |