Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
The concepts of breadth-first search (bfs) and depth-first search (dfs) algorithms, their differences, and the analysis of their time complexity. Additionally, it discusses the shortest paths problem and its solution using dijkstra's algorithm.
Typology: Study notes
1 / 10
Jared Saia
University of New Mexico
BFS and DFS Wrapup
Shortest Paths
Traverse(s){
while (the bag is not empty){put (nil,s) in bag;
if (v is unmarked)take some edge (p,v) from the bag
for each edge (v,w) incident to v{parent(v) = p;mark v;
put (v,w) into the bag;
If we implement the ābagā by using a stack, we have
Depth
First Search
If we implement the ābagā by using a queue, we have
Breadth
First Search
we implement the bag)for the āforā loop is only a constant per edge (no matter howNote that if we use adjacency lists for the graph, the overhead
operation on the bag takes constant timeIf we implement the bag using either stacks or queues, each
Hence the overall runtime is
trees are short and fatNote that DFS trees tend to be long and skinny while BFS
In addition, the BFS tree contains
shortest paths
from the
start vertex
s
to every other vertex in its connected compo-
of edges in the path)nent. (here we define the length of a path to be the number
Now assume the edges are weighted
If we implement the ābagā using a
priority queue
always
have a version of Primās algorithmextracting the minimum weight edge from the bag, then we
Each extraction from the ābagā now takes
) time so
the total running time is
(^) log
a
b
e^ d
f
c
a
b
e d
f
c
of one component of the example graph, with start vertex A depth-first spanning tree and a breadth-first spanning tree
a .
the connected component of the start vertex If the graph is disconnected, then Traverse only visits nodes in
s .
If we want to
visit
all
vertices,
we
can
use
the
following
āwrapperā
around
TraverseAll(){Traverse
for all vertices v{
if (v is unmarked){
Traverse(v);
and directed graphsNote that we can do DFS and BFS equally well on undirected
If the graph is undirected, there are two types of edges in
not in this treeedges that are in the DFS or BFS tree and edges that are
If the graph is directed, there are several types of edges
Tree edges
are edges that are in the tree itself
Back edges
are those edges (
u, v
) connecting a vertex
u
to
an ancestor
v
in the DFS tree
Forward edges
are nontree edges (
u, v
) that connect a vertex
u
to a descendant in a DFS tree
Cross edges
are all other edges.
They go between two ver-
tices where neither vertex is a descendant of the other
Useful Fact:
A directed graph
is acyclic if and only if a
DFS of
yeilds no back edges
Challenge: Try to prove this fact.
BFS and DFS are two useful algorithms for exploring graphs
algorithm.Each of these algorithms is an instantiation of the Traverse
BFS uses a queue to hold the edges and DFS
uses a stack
the nodes which are reachable from the start nodeEach of these algorithms constructs a spanning tree of all
s
Another
interesting
problem
for
graphs
is
that
of
finding
shortest paths
Assume we are given a weighted
directed
graph
with two special vertices, a source
s
and a target
t
We want to find the shortest directed path from
s
to
t
In other words, we want to find the path
p
starting at
s
and
ending at
t
minimizing the function
w
( p ) =
e ā ā p w
( e )
querque,NM to Seattle,WAImagine we want to find the fastest way to drive from Albu-
roads, weights are driving times,We might use a graph whose vertices are cities, edges are
s
is Albuquerque and
t
is
Seattle
road might be different in different directions (e.g.The graph is directed since driving times along the same
because
of construction, speed traps, etc)
the following more generalEvery algorithm known for solving this problem actually solves
single source shortest paths
or
SSSP problem:
Find the shortest path from the source vertex
s
to
every
other vertex in the graph
This problem is usually solved by finding a
shortest path tree
rooted at
s
that contains all the desired shortest paths
then they form a treeItās not hard to see that if the shortest paths are unique,
shortest paths are themselves shortest pathsTo prove this, we need only observe that the sub-paths of
paths is a treecan always choose just one of them, so that the union of theIf there are multiple shotest paths to the same vertex, we
If there are shortest paths to two vertices
u
and
v
which
of the paths so that the two paths diverge once only.diverge, then meet, then diverge again, we can modify one
s
v u
a
b
c
d
x
y
If
s ā a ā b ā c ā d ā v
and
s ā a ā x ā y ā d ā u
are both
shortest paths,
then
s
ā
a
ā
b (^) ā
c ā
d
ā
u
is also a shortest path.
can be differentNote that the minimum spanning tree and shortest path tree
multiple shortest path trees (one for every source vertex)For one thing there may be only one MST but there can be
8
5
10
2
3
18
16
12
14
30
4
26
8
5
10
2
3
18
16
12
14
30
4
26
A minimum spanning tree (left) and a shortest path tree rooted at the
topmost vertex (right).
Weāll actually allow negative weights on edges
no shortest pathThe presence of a negative cycle might mean that there is
A shortest path from
s
to
t
exists if and only if there is
at
least one
path from
s
to
t
but no path from
s
to
t
that
touches a negative cycle
In the following example, there is no shortest path from
s
to
t
s
t
5
(^2)
ā
(^4)
1
3
graphs.Weāll now go over some algorithms for SSSP on directed
modificationThese algorithms will work for undirected graphs with slight
and forth across the same undirected negative-weight edgeIn particular, we must specifically prohibit alternating back
cial cases of a single generic algorithmLike for graph traversal, all the SSSP algorithms will be spe-
Each vertex
v
in the graph will store two values which describe
a
tentative
shortest path from
s
to
v
dist
v ) is the length of the tentative shortest path between
s
and
v
pred
v ) is the predecessor of
v
in this tentative shortest path
The
predecessor
pointers
automatically
define
a
tentative
shortest path tree
Initially we set:
dist
s ) = 0,
pred
s ) =
For every vertex
v
s ,
dist
v ) =
and
pred
v ) =
We call an edge (
u, v
tense
if
dist
u ) +
(^) w
( u, v
< dist
v )
If (
u, v
) is tense, then the tentative shortest path from
s
to
v
is incorrect since the path
s
to
u
and then (
u, v
) is shorter
graph andOur generic algorithm repeatedly finds a tense edge in the
relaxes
it
have our desired shortest path treeIf there are no tense edges, our algorithm is finished and we
Relax(u,v){
pred(v) = u;dist(v) = dist(u) + w(u,v);
from three simple claimsThe correctness of the relaxation algorithm follows directly
we make choices about which edges to relaxThe run time of the algorithm will depend on the way that
If
dist
v )
, then
dist
v ) is the total weight of the prede-
cessor chain ending at
v :
s
ā Ā· Ā· Ā· ā
pred
pred
v ))
pred
v )
ā
(^) v.
in the path fromThis is easy to prove by induction on the number of edges
s
to
v
. (left as an exercise)
If the algorithm halts, then
dist
v )
ā¤
w
( s
;
v ) for
any
path
s
;
v .
in the pathThis is easy to prove by induction on the number of edges
s
;
(^) v
. (which you will do in the hw)
reachable fromThe algorithm halts if and only if there is no negative cycle
s .
cyclecycle, then after the first edge in the cycle is relaxed, theThe āonly ifā direction is easyāif there is a reachable negative
always
has at least one tense edge.
step reduces either the number of vertices withThe āifā direction follows from the fact that every relaxation
dist
v ) =
by some positive amount. by 1 or reduces the sum of the finite shortest path lengths
or what order to relax them inWe havenāt yet said how to detect which edges can be relaxed
tionsThe following Generic SSSP algorithm answers these ques-
the source vertexWe will maintain a ābagā of vertices initially containing just
s
Whenever we take a vertex
u
out of the bag, we scan all of
its outgoing edges, looking for something to relax
Whenever we successfully relax an edge (
u, v
), we put
v
in
the bag
InitSSSP(s){
for all vertices v != s{pred(s) = NULL;dist(s) = 0;
pred(v) = NULL;dist(v) = infinity;
GenericSSSP(s){
while the bag is not empty{put s in the bag;InitSSSP(s);
for all edges (u,v){take u from the bag;
if (u,v) is tense{
put v in the bag;Relax(u,v);
for the bag gives us different algorithmsJust as with graph traversal, using different data structures
Some obvious choices are: a stack, a queue and a heap
Unfortunately if we use a stack, we need to perform Ī(
|E
| )
student)relaxation steps in the worst case (an exercise for the diligent
The other possibilities are more efficient
v If we implement the bag as a heap, where the key of a vertex
is
dist
v ), we obtain Dijkstraās algorithm
negative-weight edgesDijkstraās algorithm does particularly well if the graph has no
thatIn this case, itās not hard to show (by induction, of course)
the
vertices
are
scanned
in
increasing
order
of
their
shortest-path distance from
s
that each edge is relaxed at most onceIt follows that each vertex is scanned at most once, and thus
tance fromSince the key of each vertex in the heap is its tentative dis-
s , the algorithm performs a DecreaseKey opera-
tion every time an edge is relaxed
Thus the algorithm performs at most
DecreaseKeyās
Similarly, there are at most
Insert and ExtractMin oper-
ations
running time of Dijkstraās algorithm isThus if we store the vertices in a Fibonacci heap, the total
(^) log
This analysis assumes that no edge has negative weight
tialweight edges but the worst-case run time could be exponen-The algorithm given here is still correct if there are negative
graphs with negative edges (which they make clear)The algorithm in our text book gives incorrect results for
1
(^3)
2
(^0)
5
10
12
8
4
(^6)
(^37)
s
ā ā
ā
ā
4
3
1
(^3)
2
(^0)
5
10
12
8
4
(^6)
(^37)
s 0
ā ā
ā
ā ā
ā
1
(^3)
2
(^0)
5
10
12
8
4
(^6)
(^37)
s
ā ā
4 ā
3 12
1
(^3)
2
(^0)
5
10
12
8
4
(^6)
(^37)
s
ā
4 ā
3 9
4
1
(^3)
2
(^0)
5
10
12
8
4
(^6)
(^37)
s 4
3 9
4
7
14
(^0)
0
(^0)
0
At each phase, the shaded vertices are in the heap, and the bold vertex has Four phases of Dijkstraās algorithm run on a graph with no negative edges.
just been scanned.
The bold edges describe the evolving shortest path tree.