Graphs Bfs Dfs
Graphs Bfs Dfs
• Course Handout
• Communicate through eMail
• Office hours
• To be communicated
• Grading policy
• Will be communicated as per university guidelines
• Textbook
•Introduction to Algorithms 3rd ,Cormen, Leiserson, Rivest
and Stein, The MIT Press,
•Fundamentals of Computer Algorithms, 2nd, Sartaj Sahni,
Ellis Horowitz, Sanguthevar Rajasekaran
• Others
•Introduction to Design & Analysis Computer Algorithm 3rd,
Sara Baase, Allen Van Gelder, Adison-Wesley, 2000.
•Algorithms, Richard Johnsonbaugh, Marcus Schaefer, Prentice
Hall, 2004.
•Introduction to The Design and Analysis of Algorithms 2nd
Edition, Anany Levitin, Adison-Wesley, 2007.
◼ Graph representation.
r s t u
0
v w x y
Q: s
0
CS3102 (DAA), Dept. of CSE 20
Example (BFS)
r s t u
1 0
1
v w x y
Q: w r
1 1
CS3102 (DAA), Dept. of CSE 21
Example (BFS)
r s t u
1 0 2
1 2
v w x y
Q: r t x
1 2 2
CS3102 (DAA), Dept. of CSE 22
Example (BFS)
r s t u
1 0 2
2 1 2
v w x y
Q: t x v
2 2 2
CS3102 (DAA), Dept. of CSE 23
Example (BFS)
r s t u
1 0 2 3
2 1 2
v w x y
Q: x v u
2 2 3
CS3102 (DAA), Dept. of CSE 24
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: v u y
2 3 3
CS3102 (DAA), Dept. of CSE 25
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: u y
3 3
CS3102 (DAA), Dept. of CSE 26
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: y
3
CS3102 (DAA), Dept. of CSE 27
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q:
r s t u
1 0 2 3
2 1 2 3
v w x y
BFS Tree
DFS-VISIT(u)
1 color[u] ← GRAY ▹White vertex u has just been discovered.
2 time ← time +1
3 d[u] = time // record the discovery time
4 for each v ∈ Adj[u] ▹Explore edge(u, v).
5 do if color[v] = WHITE
6 then π[v] ← u // set the parent value Can Uses a global
7 DFS-VISIT(v) // recursive call timestamp time.
8 color[u] = BLACK ▹ Blacken u; it is finished.
9 f [u] ▹ time ← time +1
◼ Lines 5-7 take time Θ(V), excluding the time to call the DFS-VISIT.
◼ DFS-VISIT is called only once for each node (since it’s called only for
white nodes and the first step in it is to paint the node gray).
◼ Loop on line 4-7 is executed |Adj(v)| times. Since, ∑vєV |Adj(v)| = Ө (E),
the total cost of DFS-VISIT is θ(E)
u v w
1/
x y z
u v w
1/ 2/
x y z
u v w
1/ 2/
3/
x y z
u v w
1/ 2/
4/ 3/
x y z
u v w
1/ 2/
B
4/ 3/
x y z
u v w
1/ 2/
B
4/5 3/
x y z
u v w
1/ 2/
B
4/5 3/6
x y z
u v w
1/ 2/7
B
4/5 3/6
x y z
u v w
1/ 2/7
F B
4/5 3/6
x y z
u v w
1/8 2/7
F B
4/5 3/6
x y z
u v w
1/8 2/7 9/
F B
4/5 3/6
x y z
u v w
1/8 2/7 9/
F B C
4/5 3/6
x y z
u v w
1/8 2/7 9/
F B C
u v w
1/8 2/7 9/
F B C
u v w
1/8 2/7 9/
F B C
u v w
1/8 2/7 9/12
F B C
◼ Applications of DFS
❑ Topologically sorting a directed acyclic graph.
◼ List the graph elements in such an order that all the nodes are listed
before nodes to which they have outgoing edges.
❑ Finding the strongly connected components of a directed graph.
◼ List all the subgraphs of a strongly connected graph which
themselves are strongly connected.