ā¹ļø 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.3 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_bellmanford.php |
| Last Crawled | 2026-03-31 23:51:30 (9 days ago) |
| First Indexed | 2024-01-30 21:46:58 (2 years ago) |
| HTTP Status Code | 200 |
| Meta Title | DSA Bellman-Ford 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
Bellman-Ford Algorithm
The Bellman-Ford Algorithm
The Bellman-Ford algorithm is best suited to find the shortest paths in a directed graph, with one or more negative edge weights, from the source vertex to all other vertices.
It does so by repeatedly checking all the edges in the graph for shorter paths, as many times as there are vertices in the graph (minus 1).
The Bellman-Ford algorithm can also be used for graphs with positive edges (both directed and undirected), like we can with Dijkstra's algorithm, but Dijkstra's algorithm is preferred in such cases because it is faster.
Using the Bellman-Ford algorithm on a graph with negative cycles will not produce a result of shortest paths because in a negative cycle we can always go one more round and get a shorter path.
A negative cycle is a path we can follow in circles, where the sum of the edge weights is negative.
Luckily, the Bellman-Ford algorithm can be implemented to safely detect and report the presence of negative cycles.
How it works:
Set initial distance to zero for the source vertex, and set initial distances to infinity for all other vertices.
For each edge, check if a shorter distance can be calculated, and update the distance if the calculated distance is shorter.
Check all edges (step 2)
V
ā
1
times. This is as many times as there are vertices (
V
), minus one.
Optional: Check for negative cycles. This will be explained in better detail later.
The animation of the Bellman-Ford algorithm above only shows us when checking of an edge leads to an updated distance, not all the other edge checks that do not lead to updated distances.
Manual Run Through
The Bellman-Ford algorithm is actually quite straight forward, because it checks all edges, using the adjacency matrix. Each check is to see if a shorter distance can be made by going from the vertex on one side of the edge, via the edge, to the vertex on the other side of the edge.
And this check of all edges is done
V
ā
1
times, with
V
being the number of vertices in the graph.
This is how the Bellman-Ford algorithm checks all the edges in the adjacency matrix in our graph 5-1=4 times:
4
-3
3
3
B
C
-4
2
4
7
5
A
E
D
A
B
C
D
E
A
B
C
D
E
4
5
-4
-3
4
7
3
2
3
Checked all edges
0
times.
The first four edges that are checked in our graph are A->C, A->E, B->C, and C->A. These first four edge checks do not lead to any updates of the shortest distances because the starting vertex of all these edges has an infinite distance.
4
-3
3
3
B
inf
C
inf
-4
2
4
7
5
A
inf
E
inf
D
0
After the edges from vertices A, B, and C are checked, the edges from D are checked. Since the starting point (vertex D) has distance 0, the updated distances for A, B, and C are the edge weights going out from vertex D.
4
-3
3
3
B
inf
C
7
-4
2
4
7
5
A
4
E
3
D
0
The next edges to be checked are the edges going out from vertex E, which leads to updated distances for vertices B and C.
4
-3
3
3
B
5
C
6
-4
2
4
7
5
A
4
E
3
D
0
The Bellman-Ford algorithm have now checked all edges 1 time. The algorithm will check all edges 3 more times before it is finished, because Bellman-Ford will check all edges as many times as there are vertices in the graph, minus 1.
The algorithm starts checking all edges a second time, starting with checking the edges going out from vertex A. Checking the edges A->C and A->E do not lead to updated distances.
4
-3
3
3
B
5
C
6
-4
2
4
7
5
A
4
E
3
D
0
The next edge to be checked is B->C, going out from vertex B. This leads to an updated distance from vertex D to C of 5-4=1.
4
-3
3
3
B
5
C
1
-4
2
4
7
5
A
4
E
3
D
0
Checking the next edge C->A, leads to an updated distance 1-3=-2 for vertex A.
4
-3
3
3
B
5
C
1
-4
2
4
7
5
A
-2
E
3
D
0
The check of edge C->A in round 2 of the Bellman-Ford algorithm is actually the last check that leads to an updated distance for this specific graph. The algorithm will continue to check all edges 2 more times without updating any distances.
Checking all edges
V
ā
1
times in the Bellman-Ford algorithm may seem like a lot, but it is done this many times to make sure that the shortest distances will always be found.
Implementation of The Bellman-Ford Algorithm
Implementing the Bellman-Ford algorithm is very similar to
how we implemented Dijkstra's algorithm
.
We start by creating the
Graph
class, where the methods
__init__
,
add_edge
, and
add_vertex
will be used to create the specific graph we want to run the Bellman-Ford algorithm on to find the shortest paths.
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
The
bellman_ford
method is also placed inside the
Graph
class. It is this method that runs the Bellman-Ford algorithm.
def
bellman_ford
(
self
,
start_vertex_data
)
:
start_vertex
=
self
.
vertex_data
.
index
(
start_vertex_data
)
distances
=
[
float
(
'inf'
)
]
*
self
.
size
distances
[
start_vertex
]
=
0
for
i
in
range
(
self
.
size
-
1
)
:
for
u
in
range
(
self
.
size
)
:
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
:
if
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
<
distances
[
v
]
:
distances
[
v
]
=
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
print
(
f"Relaxing edge
{
self
.
vertex_data
[
u
]
}
-
{
self
.
vertex_data
[
v
]
}
, Updated distance to
{
self
.
vertex_data
[
v
]
}
:
{
distances
[
v
]
}
"
)
return
distances
Line 18-19:
At the beginning, all vertices are set to have an infinite long distance from the starting vertex, except for the starting vertex itself, where the distance is set to 0.
Line 21:
All edges are checked
V
ā
1
times.
Line 22-23:
A double for-loop checks all the edges in the adjacency matrix. For every vertex
u
, check edges going to vertices
v
.
Line 24-26:
If the edge exist, and if the calculated distance is shorter than the existing distance, update the distance to that vertex
v
.
The complete code, including the initialization of our specific graph and code for running the Bellman-Ford algorithm, 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
bellman_ford
(
self
,
start_vertex_data
)
:
start_vertex
=
self
.
vertex_data
.
index
(
start_vertex_data
)
distances
=
[
float
(
'inf'
)
]
*
self
.
size
distances
[
start_vertex
]
=
0
for
i
in
range
(
self
.
size
-
1
)
:
for
u
in
range
(
self
.
size
)
:
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
:
if
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
<
distances
[
v
]
:
distances
[
v
]
=
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
print
(
f"Relaxing edge
{
self
.
vertex_data
[
u
]
}
-
{
self
.
vertex_data
[
v
]
}
, Updated distance to
{
self
.
vertex_data
[
v
]
}
:
{
distances
[
v
]
}
"
)
return
distances
g
=
Graph
(
5
)
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_edge
(
3
,
0
,
4
)
# D -> A, weight 4
g
.
add_edge
(
3
,
2
,
7
)
# D -> C, weight 7
g
.
add_edge
(
3
,
4
,
3
)
# D -> E, weight 3
g
.
add_edge
(
0
,
2
,
4
)
# A -> C, weight 4
g
.
add_edge
(
2
,
0
,
-
3
)
# C -> A, weight -3
g
.
add_edge
(
0
,
4
,
5
)
# A -> E, weight 5
g
.
add_edge
(
4
,
2
,
3
)
# E -> C, weight 3
g
.
add_edge
(
1
,
2
,
-
4
)
# B -> C, weight -4
g
.
add_edge
(
4
,
1
,
2
)
# E -> B, weight 2
# Running the Bellman-Ford algorithm from D to all vertices
print
(
"\nThe Bellman-Ford Algorithm starting from vertex D:"
)
distances
=
g
.
bellman_ford
(
'D'
)
for
i
,
d
in
enumerate
(
distances
)
:
print
(
f"Distance from D to
{
g
.
vertex_data
[
i
]
}
:
{
d
}
"
)
Try it Yourself Ā»
Negative Edges in The Bellman-Ford Algorithm
To say that the Bellman-Ford algorithm finds the "shortest paths" is not intuitive, because how can we draw or imagine distances that are negative? So, to make it easier to understand we could instead say that it is the "
cheapest
paths" that are found with Bellman-Ford.
In practice, the Bellman-Ford algorithm could for example help us to find delivering routes where the edge weights represent the cost of fuel and other things, minus the money to be made by driving that edge between those two vertices.
4
-3
3
3
B
5
C
1
-4
2
4
7
5
A
-2
E
3
D
0
With this interpretation in mind, the -3 weight on edge C->A could mean that the fuel cost is $5 driving from C to A, and that we get paid $8 for picking up packages in C and delivering them in A. So we end up earning $3 more than we spend. Therefore, a total of $2 can be made by driving the delivery route D->E->B->C->A in our graph above.
Negative Cycles in The Bellman-Ford Algorithm
If we can go in circles in a graph, and the sum of edges in that circle is negative, we have a negative cycle.
4
-9
3
3
B
C
-4
2
4
7
5
A
E
D
By changing the weight on edge C->A from -3 to -9, we get two negative cycles: A->C->A and A->E->C->A. And every time we check these edges with the Bellman-Ford algorithm, the distances we calculate and update just become lower and lower.
The problem with negative cycles is that a shortest path does not exist, because we can always go one more round to get a path that is shorter.
That is why it is useful to implement the Bellman-Ford algorithm with detection for negative cycles.
Detection of Negative Cycles in the Bellman-Ford Algorithm
After running the Bellman-Ford algorithm, checking all edges in a graph
V
ā
1
times, all the shortest distances are found.
But, if the graph contains negative cycles, and we go one more round checking all edges, we will find at least one shorter distance in this last round, right?
So to detect negative cycles in the Bellman-Ford algorithm, after checking all edges
V
ā
1
times, we just need to check all edges one more time, and if we find a shorter distance this last time, we can conclude that a negative cycle must exist.
Below is the
bellman_ford
method, with negative cycle detection included, running on the graph above with negative cycles due to the C->A edge weight of -9:
Example
Python:
def
bellman_ford
(
self
,
start_vertex_data
)
:
start_vertex
=
self
.
vertex_data
.
index
(
start_vertex_data
)
distances
=
[
float
(
'inf'
)
]
*
self
.
size
distances
[
start_vertex
]
=
0
for
i
in
range
(
self
.
size
-
1
)
:
for
u
in
range
(
self
.
size
)
:
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
:
if
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
<
distances
[
v
]
:
distances
[
v
]
=
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
print
(
f"Relaxing edge
{
self
.
vertex_data
[
u
]
}
->
{
self
.
vertex_data
[
v
]
}
, Updated distance to
{
self
.
vertex_data
[
v
]
}
:
{
distances
[
v
]
}
"
)
# Negative cycle detection
for
u
in
range
(
self
.
size
)
:
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
:
if
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
<
distances
[
v
]
:
return
(
True
,
None
)
# Indicate a negative cycle was found
return
(
False
,
distances
)
# Indicate no negative cycle and return distances
Try it Yourself Ā»
Line 30-33:
All edges are checked one more time to see if there are negative cycles.
Line 34:
Returning
True
indicates that a negative cycle exists, and
None
is returned instead of the shortest distances, because finding the shortest distances in a graph with negative cycles does not make sense (because a shorter distance can always be found by checking all edges one more time).
Line 36:
Returning
False
means that there is no negative cycles, and the
distances
can be returned.
Returning The Paths from The Bellman-Ford Algorithm
We are currently finding the total weight of the the shortest paths, so that for example "Distance from D to A: -2" is a result from running the Bellman-Ford algorithm.
But by recording the predecessor of each vertex whenever an edge is relaxed, we can use that later in our code to print the result including the actual shortest paths. This means we can give more information in our result, with the actual path in addition to the path weight: "D->E->B->C->A, Distance: -2".
This last code example is the complete code for the Bellman-Ford algorithm, with everything we have discussed up until now: finding the weights of shortest paths, detecting negative cycles, and finding the actual shortest paths:
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
bellman_ford
(
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
for
i
in
range
(
self
.
size
-
1
)
:
for
u
in
range
(
self
.
size
)
:
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
:
if
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
<
distances
[
v
]
:
distances
[
v
]
=
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
predecessors
[
v
]
=
u
print
(
f"Relaxing edge
{
self
.
vertex_data
[
u
]
}
->
{
self
.
vertex_data
[
v
]
}
, Updated distance to
{
self
.
vertex_data
[
v
]
}
:
{
distances
[
v
]
}
"
)
# Negative cycle detection
for
u
in
range
(
self
.
size
)
:
for
v
in
range
(
self
.
size
)
:
if
self
.
adj_matrix
[
u
]
[
v
]
!=
0
:
if
distances
[
u
]
+
self
.
adj_matrix
[
u
]
[
v
]
<
distances
[
v
]
:
return
(
True
,
None
,
None
)
# Indicate a negative cycle was found
return
(
False
,
distances
,
predecessors
)
# Indicate no negative cycle and return distances
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
)
g
=
Graph
(
5
)
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_edge
(
3
,
0
,
4
)
# D -> A, weight 4
g
.
add_edge
(
3
,
2
,
7
)
# D -> C, weight 7
g
.
add_edge
(
3
,
4
,
3
)
# D -> E, weight 3
g
.
add_edge
(
0
,
2
,
4
)
# A -> C, weight 4
g
.
add_edge
(
2
,
0
,
-
3
)
# C -> A, weight -3
g
.
add_edge
(
0
,
4
,
5
)
# A -> E, weight 5
g
.
add_edge
(
4
,
2
,
3
)
# E -> C, weight 3
g
.
add_edge
(
1
,
2
,
-
4
)
# B -> C, weight -4
g
.
add_edge
(
4
,
1
,
2
)
# E -> B, weight 2
# Running the Bellman-Ford algorithm from D to all vertices
print
(
"\nThe Bellman-Ford Algorithm starting from vertex D:"
)
negative_cycle
,
distances
,
predecessors
=
g
.
bellman_ford
(
'D'
)
if
not
negative_cycle
:
for
i
,
d
in
enumerate
(
distances
)
:
if
d
!=
float
(
'inf'
)
:
path
=
g
.
get_path
(
predecessors
,
'D'
,
g
.
vertex_data
[
i
]
)
print
(
f"
{
path
}
, Distance:
{
d
}
"
)
else
:
print
(
f"No path from D to
{
g
.
vertex_data
[
i
]
}
, Distance: Infinity"
)
else
:
print
(
"Negative weight cycle detected. Cannot compute shortest paths."
)
Try it Yourself Ā»
Line 19:
The
predecessors
array holds each vertex' predecessor vertex in the shortest path.
Line 28:
The
predecessors
array gets updated with the new predecessor vertex every time an edge is relaxed.
Line 40-49:
The
get_path
method uses the
predecessors
array to generate the shortest path string for each vertex.
Time Complexity for The Bellman-Ford Algorithm
The time complexity for the Bellman-Ford algorithm mostly depends on the nested loops.
The outer for-loop
runs
V
ā
1
times, or
V
times in case we also have negative cycle detection. For graphs with many vertices, checking all edges one less time than there are vertices makes little difference, so we can say that the outer loop contributes with
O
(
V
)
to the time complexity.
The two inner for-loops
checks all edges in the graph. If we assume a worst case scenario in terms of time complexity, then we have a very dense graph where every vertex has an edge to every other vertex, so for all vertex
V
the edge to all other vertices
V
must be checked, which contributes with
O
(
V
2
)
to the time complexity.
So in total, we get the time complexity for the Bellman-Ford algorithm:
O
(
V
3
)
However, in practical situations and especially for sparse graphs, meaning each vertex only has edges to a small portion of the other vertices, time complexity of the two inner for-loops checking all edges can be approximated from
O
(
V
2
)
to
O
(
E
)
, and we get the total time complexity for Bellman-Ford:
O
(
V
ā
E
)
The time complexity for the Bellman-Ford algorithm is slower than for Dijkstra's algorithm, but Bellman-Ford can find the shortest paths in graphs with negative edges and it can detect negative cycles, which Dijkstra's algorithm cannot do.
DSA Exercises
Test Yourself With Exercises
Exercise:
In the adjacency matrix below:
What is the edge weight of the edge going from D to E?
The D->E edge weight is
.
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_bellmanford.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_bellmanford.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 Bellman-Ford Algorithm
[ā® Previous](https://www.w3schools.com/dsa/dsa_algo_graphs_dijkstra.php) [Next āÆ](https://www.w3schools.com/dsa/dsa_theory_mst_minspantree.php)
***
## The Bellman-Ford Algorithm
The Bellman-Ford algorithm is best suited to find the shortest paths in a directed graph, with one or more negative edge weights, from the source vertex to all other vertices.
It does so by repeatedly checking all the edges in the graph for shorter paths, as many times as there are vertices in the graph (minus 1).
4
\-3
3
3
B
inf
C
inf
\-4
2
4
7
5
A
inf
E
inf
D
0
4
7
3
2
3
3
3
\-4
5
1
\-3
Play
Reset
The Bellman-Ford algorithm can also be used for graphs with positive edges (both directed and undirected), like we can with Dijkstra's algorithm, but Dijkstra's algorithm is preferred in such cases because it is faster.
Using the Bellman-Ford algorithm on a graph with negative cycles will not produce a result of shortest paths because in a negative cycle we can always go one more round and get a shorter path.
A negative cycle is a path we can follow in circles, where the sum of the edge weights is negative.
Luckily, the Bellman-Ford algorithm can be implemented to safely detect and report the presence of negative cycles.
**How it works:**
1. Set initial distance to zero for the source vertex, and set initial distances to infinity for all other vertices.
2. For each edge, check if a shorter distance can be calculated, and update the distance if the calculated distance is shorter.
3. Check all edges (step 2)
Vā1
V
ā
1
times. This is as many times as there are vertices (
V
V
), minus one.
4. Optional: Check for negative cycles. This will be explained in better detail later.
The animation of the Bellman-Ford algorithm above only shows us when checking of an edge leads to an updated distance, not all the other edge checks that do not lead to updated distances.
***
[REMOVE ADS](https://order.w3schools.com/plans)
***
## Manual Run Through
The Bellman-Ford algorithm is actually quite straight forward, because it checks all edges, using the adjacency matrix. Each check is to see if a shorter distance can be made by going from the vertex on one side of the edge, via the edge, to the vertex on the other side of the edge.
And this check of all edges is done Vā1 V ā 1 times, with V V being the number of vertices in the graph.
This is how the Bellman-Ford algorithm checks all the edges in the adjacency matrix in our graph 5-1=4 times:
4
\-3
3
3
B
C
\-4
2
4
7
5
A
E
D
4
\-3
3
3
\-4
2
4
7
5
A
B
C
D
E
A
B
C
D
E
4
5
\-4
\-3
4
7
3
2
3
Checked all edges 0 times.
Play
Reset
The first four edges that are checked in our graph are A-\>C, A-\>E, B-\>C, and C-\>A. These first four edge checks do not lead to any updates of the shortest distances because the starting vertex of all these edges has an infinite distance.
4
\-3
3
3
B
inf
C
inf
\-4
2
4
7
5
A
inf
E
inf
D
0
After the edges from vertices A, B, and C are checked, the edges from D are checked. Since the starting point (vertex D) has distance 0, the updated distances for A, B, and C are the edge weights going out from vertex D.
4
\-3
3
3
B
inf
C
7
\-4
2
4
7
5
A
4
E
3
D
0
The next edges to be checked are the edges going out from vertex E, which leads to updated distances for vertices B and C.
4
\-3
3
3
B
5
C
6
\-4
2
4
7
5
A
4
E
3
D
0
The Bellman-Ford algorithm have now checked all edges 1 time. The algorithm will check all edges 3 more times before it is finished, because Bellman-Ford will check all edges as many times as there are vertices in the graph, minus 1.
The algorithm starts checking all edges a second time, starting with checking the edges going out from vertex A. Checking the edges A-\>C and A-\>E do not lead to updated distances.
4
\-3
3
3
B
5
C
6
\-4
2
4
7
5
A
4
E
3
D
0
The next edge to be checked is B-\>C, going out from vertex B. This leads to an updated distance from vertex D to C of 5-4=1.
4
\-3
3
3
B
5
C
1
\-4
2
4
7
5
A
4
E
3
D
0
Checking the next edge C-\>A, leads to an updated distance 1-3=-2 for vertex A.
4
\-3
3
3
B
5
C
1
\-4
2
4
7
5
A
\-2
E
3
D
0
The check of edge C-\>A in round 2 of the Bellman-Ford algorithm is actually the last check that leads to an updated distance for this specific graph. The algorithm will continue to check all edges 2 more times without updating any distances.
Checking all edges Vā1 V ā 1 times in the Bellman-Ford algorithm may seem like a lot, but it is done this many times to make sure that the shortest distances will always be found.
***
## Implementation of The Bellman-Ford Algorithm
Implementing the Bellman-Ford algorithm is very similar to [how we implemented Dijkstra's algorithm](https://www.w3schools.com/dsa/dsa_algo_graphs_dijkstra.php#dijkstraImpl).
We start by creating the `Graph` class, where the methods `__init__`, `add_edge`, and `add_vertex` will be used to create the specific graph we want to run the Bellman-Ford algorithm on to find the shortest paths.
```
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
```
The `bellman_ford` method is also placed inside the `Graph` class. It is this method that runs the Bellman-Ford algorithm.
```
```
**Line 18-19:** At the beginning, all vertices are set to have an infinite long distance from the starting vertex, except for the starting vertex itself, where the distance is set to 0.
**Line 21:** All edges are checked Vā1 V ā 1 times.
**Line 22-23:** A double for-loop checks all the edges in the adjacency matrix. For every vertex `u`, check edges going to vertices `v`.
**Line 24-26:** If the edge exist, and if the calculated distance is shorter than the existing distance, update the distance to that vertex `v`.
The complete code, including the initialization of our specific graph and code for running the Bellman-Ford algorithm, 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 bellman_ford(self, start_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
distances = [float('inf')] * self.size
distances[start_vertex] = 0
for i in range(self.size - 1):
for u in range(self.size):
for v in range(self.size):
if self.adj_matrix[u][v] != 0:
if distances[u] + self.adj_matrix[u][v] < distances[v]:
distances[v] = distances[u] + self.adj_matrix[u][v]
print(f"Relaxing edge {self.vertex_data[u]}-{self.vertex_data[v]}, Updated distance to {self.vertex_data[v]}: {distances[v]}")
return distances
g = Graph(5)
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_edge(3, 0, 4) # D -> A, weight 4
g.add_edge(3, 2, 7) # D -> C, weight 7
g.add_edge(3, 4, 3) # D -> E, weight 3
g.add_edge(0, 2, 4) # A -> C, weight 4
g.add_edge(2, 0, -3) # C -> A, weight -3
g.add_edge(0, 4, 5) # A -> E, weight 5
g.add_edge(4, 2, 3) # E -> C, weight 3
g.add_edge(1, 2, -4) # B -> C, weight -4
g.add_edge(4, 1, 2) # E -> B, weight 2
# Running the Bellman-Ford algorithm from D to all vertices
print("\nThe Bellman-Ford Algorithm starting from vertex D:")
distances = g.bellman_ford('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_bellmanford)
***
## Negative Edges in The Bellman-Ford Algorithm
To say that the Bellman-Ford algorithm finds the "shortest paths" is not intuitive, because how can we draw or imagine distances that are negative? So, to make it easier to understand we could instead say that it is the "*cheapest* paths" that are found with Bellman-Ford.
In practice, the Bellman-Ford algorithm could for example help us to find delivering routes where the edge weights represent the cost of fuel and other things, minus the money to be made by driving that edge between those two vertices.
4
\-3
3
3
B
5
C
1
\-4
2
4
7
5
A
\-2
E
3
D
0
With this interpretation in mind, the -3 weight on edge C-\>A could mean that the fuel cost is \$5 driving from C to A, and that we get paid \$8 for picking up packages in C and delivering them in A. So we end up earning \$3 more than we spend. Therefore, a total of \$2 can be made by driving the delivery route D-\>E-\>B-\>C-\>A in our graph above.
***
## Negative Cycles in The Bellman-Ford Algorithm
If we can go in circles in a graph, and the sum of edges in that circle is negative, we have a negative cycle.
4
\-9
3
3
B
C
\-4
2
4
7
5
A
E
D
By changing the weight on edge C-\>A from -3 to -9, we get two negative cycles: A-\>C-\>A and A-\>E-\>C-\>A. And every time we check these edges with the Bellman-Ford algorithm, the distances we calculate and update just become lower and lower.
The problem with negative cycles is that a shortest path does not exist, because we can always go one more round to get a path that is shorter.
That is why it is useful to implement the Bellman-Ford algorithm with detection for negative cycles.
***
## Detection of Negative Cycles in the Bellman-Ford Algorithm
After running the Bellman-Ford algorithm, checking all edges in a graph Vā1 V ā 1 times, all the shortest distances are found.
But, if the graph contains negative cycles, and we go one more round checking all edges, we will find at least one shorter distance in this last round, right?
So to detect negative cycles in the Bellman-Ford algorithm, after checking all edges Vā1 V ā 1 times, we just need to check all edges one more time, and if we find a shorter distance this last time, we can conclude that a negative cycle must exist.
Below is the `bellman_ford` method, with negative cycle detection included, running on the graph above with negative cycles due to the C-\>A edge weight of -9:
### Example
Python:
```
```
[Try it Yourself Ā»](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_bellmanford_cycledetection)
**Line 30-33:** All edges are checked one more time to see if there are negative cycles.
**Line 34:** Returning `True` indicates that a negative cycle exists, and `None` is returned instead of the shortest distances, because finding the shortest distances in a graph with negative cycles does not make sense (because a shorter distance can always be found by checking all edges one more time).
**Line 36:** Returning `False` means that there is no negative cycles, and the `distances` can be returned.
***
## Returning The Paths from The Bellman-Ford Algorithm
We are currently finding the total weight of the the shortest paths, so that for example "Distance from D to A: -2" is a result from running the Bellman-Ford algorithm.
But by recording the predecessor of each vertex whenever an edge is relaxed, we can use that later in our code to print the result including the actual shortest paths. This means we can give more information in our result, with the actual path in addition to the path weight: "D-\>E-\>B-\>C-\>A, Distance: -2".
This last code example is the complete code for the Bellman-Ford algorithm, with everything we have discussed up until now: finding the weights of shortest paths, detecting negative cycles, and finding the actual shortest paths:
### Example
Python:
```
```
[Try it Yourself Ā»](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_bellmanford_paths)
**Line 19:** The `predecessors` array holds each vertex' predecessor vertex in the shortest path.
**Line 28:** The `predecessors` array gets updated with the new predecessor vertex every time an edge is relaxed.
**Line 40-49:** The `get_path` method uses the `predecessors` array to generate the shortest path string for each vertex.
***
## Time Complexity for The Bellman-Ford Algorithm
The time complexity for the Bellman-Ford algorithm mostly depends on the nested loops.
**The outer for-loop** runs Vā1 V ā 1 times, or V V times in case we also have negative cycle detection. For graphs with many vertices, checking all edges one less time than there are vertices makes little difference, so we can say that the outer loop contributes with O(V) O ( V ) to the time complexity.
**The two inner for-loops** checks all edges in the graph. If we assume a worst case scenario in terms of time complexity, then we have a very dense graph where every vertex has an edge to every other vertex, so for all vertex V V the edge to all other vertices V V must be checked, which contributes with O(V2) O ( V 2 ) to the time complexity.
So in total, we get the time complexity for the Bellman-Ford algorithm:
O(V3) O ( V 3 )
However, in practical situations and especially for sparse graphs, meaning each vertex only has edges to a small portion of the other vertices, time complexity of the two inner for-loops checking all edges can be approximated from O(V2) O ( V 2 ) to O(E) O ( E ), and we get the total time complexity for Bellman-Ford:
O(Vā
E) O ( V ā
E )
The time complexity for the Bellman-Ford algorithm is slower than for Dijkstra's algorithm, but Bellman-Ford can find the shortest paths in graphs with negative edges and it can detect negative cycles, which Dijkstra's algorithm cannot do.
***
## DSA Exercises
***
[ā® Previous](https://www.w3schools.com/dsa/dsa_algo_graphs_dijkstra.php) [Next āÆ](https://www.w3schools.com/dsa/dsa_theory_mst_minspantree.php)
[ā
+1](https://profile.w3schools.com/log-in?redirect_url=https%3A%2F%2Fwww.w3schools.com%2Fdsa%2Fdsa_algo_graphs_bellmanford.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_bellmanford.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 Bellman-Ford Algorithm
***
## The Bellman-Ford Algorithm
The Bellman-Ford algorithm is best suited to find the shortest paths in a directed graph, with one or more negative edge weights, from the source vertex to all other vertices.
It does so by repeatedly checking all the edges in the graph for shorter paths, as many times as there are vertices in the graph (minus 1).
The Bellman-Ford algorithm can also be used for graphs with positive edges (both directed and undirected), like we can with Dijkstra's algorithm, but Dijkstra's algorithm is preferred in such cases because it is faster.
Using the Bellman-Ford algorithm on a graph with negative cycles will not produce a result of shortest paths because in a negative cycle we can always go one more round and get a shorter path.
A negative cycle is a path we can follow in circles, where the sum of the edge weights is negative.
Luckily, the Bellman-Ford algorithm can be implemented to safely detect and report the presence of negative cycles.
**How it works:**
1. Set initial distance to zero for the source vertex, and set initial distances to infinity for all other vertices.
2. For each edge, check if a shorter distance can be calculated, and update the distance if the calculated distance is shorter.
3. Check all edges (step 2)
V
ā
1
times. This is as many times as there are vertices (
V
), minus one.
4. Optional: Check for negative cycles. This will be explained in better detail later.
The animation of the Bellman-Ford algorithm above only shows us when checking of an edge leads to an updated distance, not all the other edge checks that do not lead to updated distances.
***
***
## Manual Run Through
The Bellman-Ford algorithm is actually quite straight forward, because it checks all edges, using the adjacency matrix. Each check is to see if a shorter distance can be made by going from the vertex on one side of the edge, via the edge, to the vertex on the other side of the edge.
And this check of all edges is done V ā 1 times, with V being the number of vertices in the graph.
This is how the Bellman-Ford algorithm checks all the edges in the adjacency matrix in our graph 5-1=4 times:
4
\-3
3
3
B
C
\-4
2
4
7
5
A
E
D
A
B
C
D
E
A
B
C
D
E
4
5
\-4
\-3
4
7
3
2
3
Checked all edges 0 times.
The first four edges that are checked in our graph are A-\>C, A-\>E, B-\>C, and C-\>A. These first four edge checks do not lead to any updates of the shortest distances because the starting vertex of all these edges has an infinite distance.
4 \-3 3 3 B inf C inf \-4 2 4 7 5 A inf E inf D 0
After the edges from vertices A, B, and C are checked, the edges from D are checked. Since the starting point (vertex D) has distance 0, the updated distances for A, B, and C are the edge weights going out from vertex D.
4 \-3 3 3 B inf C 7 \-4 2 4 7 5 A 4 E 3 D 0
The next edges to be checked are the edges going out from vertex E, which leads to updated distances for vertices B and C.
4 \-3 3 3 B 5 C 6 \-4 2 4 7 5 A 4 E 3 D 0
The Bellman-Ford algorithm have now checked all edges 1 time. The algorithm will check all edges 3 more times before it is finished, because Bellman-Ford will check all edges as many times as there are vertices in the graph, minus 1.
The algorithm starts checking all edges a second time, starting with checking the edges going out from vertex A. Checking the edges A-\>C and A-\>E do not lead to updated distances.
4 \-3 3 3 B 5 C 6 \-4 2 4 7 5 A 4 E 3 D 0
The next edge to be checked is B-\>C, going out from vertex B. This leads to an updated distance from vertex D to C of 5-4=1.
4 \-3 3 3 B 5 C 1 \-4 2 4 7 5 A 4 E 3 D 0
Checking the next edge C-\>A, leads to an updated distance 1-3=-2 for vertex A.
4 \-3 3 3 B 5 C 1 \-4 2 4 7 5 A \-2 E 3 D 0
The check of edge C-\>A in round 2 of the Bellman-Ford algorithm is actually the last check that leads to an updated distance for this specific graph. The algorithm will continue to check all edges 2 more times without updating any distances.
Checking all edges V ā 1 times in the Bellman-Ford algorithm may seem like a lot, but it is done this many times to make sure that the shortest distances will always be found.
***
## Implementation of The Bellman-Ford Algorithm
Implementing the Bellman-Ford algorithm is very similar to [how we implemented Dijkstra's algorithm](https://www.w3schools.com/dsa/dsa_algo_graphs_dijkstra.php#dijkstraImpl).
We start by creating the `Graph` class, where the methods `__init__`, `add_edge`, and `add_vertex` will be used to create the specific graph we want to run the Bellman-Ford algorithm on to find the shortest paths.
```
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
```
The `bellman_ford` method is also placed inside the `Graph` class. It is this method that runs the Bellman-Ford algorithm.
```
def bellman_ford(self, start_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
distances = [float('inf')] * self.size
distances[start_vertex] = 0
for i in range(self.size - 1):
for u in range(self.size):
for v in range(self.size):
if self.adj_matrix[u][v] != 0:
if distances[u] + self.adj_matrix[u][v] < distances[v]:
distances[v] = distances[u] + self.adj_matrix[u][v]
print(f"Relaxing edge {self.vertex_data[u]}-{self.vertex_data[v]}, Updated distance to {self.vertex_data[v]}: {distances[v]}")
return distances
```
**Line 18-19:** At the beginning, all vertices are set to have an infinite long distance from the starting vertex, except for the starting vertex itself, where the distance is set to 0.
**Line 21:** All edges are checked V ā 1 times.
**Line 22-23:** A double for-loop checks all the edges in the adjacency matrix. For every vertex `u`, check edges going to vertices `v`.
**Line 24-26:** If the edge exist, and if the calculated distance is shorter than the existing distance, update the distance to that vertex `v`.
The complete code, including the initialization of our specific graph and code for running the Bellman-Ford algorithm, 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 bellman_ford(self, start_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
distances = [float('inf')] * self.size
distances[start_vertex] = 0
for i in range(self.size - 1):
for u in range(self.size):
for v in range(self.size):
if self.adj_matrix[u][v] != 0:
if distances[u] + self.adj_matrix[u][v] < distances[v]:
distances[v] = distances[u] + self.adj_matrix[u][v]
print(f"Relaxing edge {self.vertex_data[u]}-{self.vertex_data[v]}, Updated distance to {self.vertex_data[v]}: {distances[v]}")
return distances
g = Graph(5)
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_edge(3, 0, 4) # D -> A, weight 4
g.add_edge(3, 2, 7) # D -> C, weight 7
g.add_edge(3, 4, 3) # D -> E, weight 3
g.add_edge(0, 2, 4) # A -> C, weight 4
g.add_edge(2, 0, -3) # C -> A, weight -3
g.add_edge(0, 4, 5) # A -> E, weight 5
g.add_edge(4, 2, 3) # E -> C, weight 3
g.add_edge(1, 2, -4) # B -> C, weight -4
g.add_edge(4, 1, 2) # E -> B, weight 2
# Running the Bellman-Ford algorithm from D to all vertices
print("\nThe Bellman-Ford Algorithm starting from vertex D:")
distances = g.bellman_ford('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_bellmanford)
***
## Negative Edges in The Bellman-Ford Algorithm
To say that the Bellman-Ford algorithm finds the "shortest paths" is not intuitive, because how can we draw or imagine distances that are negative? So, to make it easier to understand we could instead say that it is the "*cheapest* paths" that are found with Bellman-Ford.
In practice, the Bellman-Ford algorithm could for example help us to find delivering routes where the edge weights represent the cost of fuel and other things, minus the money to be made by driving that edge between those two vertices.
4 \-3 3 3 B 5 C 1 \-4 2 4 7 5 A \-2 E 3 D 0
With this interpretation in mind, the -3 weight on edge C-\>A could mean that the fuel cost is \$5 driving from C to A, and that we get paid \$8 for picking up packages in C and delivering them in A. So we end up earning \$3 more than we spend. Therefore, a total of \$2 can be made by driving the delivery route D-\>E-\>B-\>C-\>A in our graph above.
***
## Negative Cycles in The Bellman-Ford Algorithm
If we can go in circles in a graph, and the sum of edges in that circle is negative, we have a negative cycle.
4 \-9 3 3 B C \-4 2 4 7 5 A E D
By changing the weight on edge C-\>A from -3 to -9, we get two negative cycles: A-\>C-\>A and A-\>E-\>C-\>A. And every time we check these edges with the Bellman-Ford algorithm, the distances we calculate and update just become lower and lower.
The problem with negative cycles is that a shortest path does not exist, because we can always go one more round to get a path that is shorter.
That is why it is useful to implement the Bellman-Ford algorithm with detection for negative cycles.
***
## Detection of Negative Cycles in the Bellman-Ford Algorithm
After running the Bellman-Ford algorithm, checking all edges in a graph V ā 1 times, all the shortest distances are found.
But, if the graph contains negative cycles, and we go one more round checking all edges, we will find at least one shorter distance in this last round, right?
So to detect negative cycles in the Bellman-Ford algorithm, after checking all edges V ā 1 times, we just need to check all edges one more time, and if we find a shorter distance this last time, we can conclude that a negative cycle must exist.
Below is the `bellman_ford` method, with negative cycle detection included, running on the graph above with negative cycles due to the C-\>A edge weight of -9:
### Example
Python:
```
def bellman_ford(self, start_vertex_data):
start_vertex = self.vertex_data.index(start_vertex_data)
distances = [float('inf')] * self.size
distances[start_vertex] = 0
for i in range(self.size - 1):
for u in range(self.size):
for v in range(self.size):
if self.adj_matrix[u][v] != 0:
if distances[u] + self.adj_matrix[u][v] < distances[v]:
distances[v] = distances[u] + self.adj_matrix[u][v]
print(f"Relaxing edge {self.vertex_data[u]}->{self.vertex_data[v]}, Updated distance to {self.vertex_data[v]}: {distances[v]}")
# Negative cycle detection
for u in range(self.size):
for v in range(self.size):
if self.adj_matrix[u][v] != 0:
if distances[u] + self.adj_matrix[u][v] < distances[v]:
return (True, None) # Indicate a negative cycle was found
return (False, distances) # Indicate no negative cycle and return distances
```
[Try it Yourself Ā»](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_bellmanford_cycledetection)
**Line 30-33:** All edges are checked one more time to see if there are negative cycles.
**Line 34:** Returning `True` indicates that a negative cycle exists, and `None` is returned instead of the shortest distances, because finding the shortest distances in a graph with negative cycles does not make sense (because a shorter distance can always be found by checking all edges one more time).
**Line 36:** Returning `False` means that there is no negative cycles, and the `distances` can be returned.
***
## Returning The Paths from The Bellman-Ford Algorithm
We are currently finding the total weight of the the shortest paths, so that for example "Distance from D to A: -2" is a result from running the Bellman-Ford algorithm.
But by recording the predecessor of each vertex whenever an edge is relaxed, we can use that later in our code to print the result including the actual shortest paths. This means we can give more information in our result, with the actual path in addition to the path weight: "D-\>E-\>B-\>C-\>A, Distance: -2".
This last code example is the complete code for the Bellman-Ford algorithm, with everything we have discussed up until now: finding the weights of shortest paths, detecting negative cycles, and finding the actual shortest paths:
### 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 bellman_ford(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
for i in range(self.size - 1):
for u in range(self.size):
for v in range(self.size):
if self.adj_matrix[u][v] != 0:
if distances[u] + self.adj_matrix[u][v] < distances[v]:
distances[v] = distances[u] + self.adj_matrix[u][v]
predecessors[v] = u
print(f"Relaxing edge {self.vertex_data[u]}->{self.vertex_data[v]}, Updated distance to {self.vertex_data[v]}: {distances[v]}")
# Negative cycle detection
for u in range(self.size):
for v in range(self.size):
if self.adj_matrix[u][v] != 0:
if distances[u] + self.adj_matrix[u][v] < distances[v]:
return (True, None, None) # Indicate a negative cycle was found
return (False, distances, predecessors) # Indicate no negative cycle and return distances
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)
g = Graph(5)
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_edge(3, 0, 4) # D -> A, weight 4
g.add_edge(3, 2, 7) # D -> C, weight 7
g.add_edge(3, 4, 3) # D -> E, weight 3
g.add_edge(0, 2, 4) # A -> C, weight 4
g.add_edge(2, 0, -3) # C -> A, weight -3
g.add_edge(0, 4, 5) # A -> E, weight 5
g.add_edge(4, 2, 3) # E -> C, weight 3
g.add_edge(1, 2, -4) # B -> C, weight -4
g.add_edge(4, 1, 2) # E -> B, weight 2
# Running the Bellman-Ford algorithm from D to all vertices
print("\nThe Bellman-Ford Algorithm starting from vertex D:")
negative_cycle, distances, predecessors = g.bellman_ford('D')
if not negative_cycle:
for i, d in enumerate(distances):
if d != float('inf'):
path = g.get_path(predecessors, 'D', g.vertex_data[i])
print(f"{path}, Distance: {d}")
else:
print(f"No path from D to {g.vertex_data[i]}, Distance: Infinity")
else:
print("Negative weight cycle detected. Cannot compute shortest paths.")
```
[Try it Yourself Ā»](https://www.w3schools.com/dsa/trydsa.php?filename=demo_graphs_bellmanford_paths)
**Line 19:** The `predecessors` array holds each vertex' predecessor vertex in the shortest path.
**Line 28:** The `predecessors` array gets updated with the new predecessor vertex every time an edge is relaxed.
**Line 40-49:** The `get_path` method uses the `predecessors` array to generate the shortest path string for each vertex.
***
## Time Complexity for The Bellman-Ford Algorithm
The time complexity for the Bellman-Ford algorithm mostly depends on the nested loops.
**The outer for-loop** runs V ā 1 times, or V times in case we also have negative cycle detection. For graphs with many vertices, checking all edges one less time than there are vertices makes little difference, so we can say that the outer loop contributes with O ( V ) to the time complexity.
**The two inner for-loops** checks all edges in the graph. If we assume a worst case scenario in terms of time complexity, then we have a very dense graph where every vertex has an edge to every other vertex, so for all vertex V the edge to all other vertices V must be checked, which contributes with O ( V 2 ) to the time complexity.
So in total, we get the time complexity for the Bellman-Ford algorithm:
O ( V 3 )
However, in practical situations and especially for sparse graphs, meaning each vertex only has edges to a small portion of the other vertices, time complexity of the two inner for-loops checking all edges can be approximated from O ( V 2 ) to O ( E ), and we get the total time complexity for Bellman-Ford:
O ( V ā
E )
The time complexity for the Bellman-Ford algorithm is slower than for Dijkstra's algorithm, but Bellman-Ford can find the shortest paths in graphs with negative edges and it can detect negative cycles, which Dijkstra's algorithm cannot do.
***
## DSA Exercises
*** |
| Shard | 40 (laksa) |
| Root Hash | 10756103332767711440 |
| Unparsed URL | com,w3schools!www,/dsa/dsa_algo_graphs_bellmanford.php s443 |