SlideShare a Scribd company logo
Elementary Graph Algorithms
Dr. AMIT KUMAR @JUET
Graphs
• Graph G = (V, E)
– V = set of vertices
– E = set of edges  (VV)
• Types of graphs
– Undirected: edge (u, v) = (v, u); for all v, (v, v)  E (No self loops.)
– Directed: (u, v) is edge from u to v, denoted as u  v. Self loops
are allowed.
– Weighted: each edge has an associated weight, given by a weight
function w : E  R.
– Dense: |E|  |V|2.
– Sparse: |E| << |V|2.
• |E| = O(|V|2)
Dr. AMIT KUMAR @JUET
Graphs
• If (u, v)  E, then vertex v is adjacent to vertex u.
• Adjacency relationship is:
– Symmetric if G is undirected.
– Not necessarily so if G is directed.
• If G is connected:
– There is a path between every pair of vertices.
– |E|  |V| – 1.
– Furthermore, if |E| = |V| – 1, then G is a tree.
• Other definitions in Appendix B (B.4 and B.5) as needed.
Dr. AMIT KUMAR @JUET
Representation of Graphs
• Two standard ways.
– Adjacency Lists.
– Adjacency Matrix.
a
dc
b a
b
c
d
b
a
d
d c
c
a b
a c
a
dc
b
1 2
3 4
1 2 3 4
1 0 1 1 1
2 1 0 1 0
3 1 1 0 1
4 1 0 1 0
Dr. AMIT KUMAR @JUET
Adjacency Lists
• Consists of an array Adj of |V| lists.
• One list per vertex.
• For u  V, Adj[u] consists of all vertices adjacent to u.
a
dc
b a
b
c
d
b
c
d
d c
a
dc
b a
b
c
d
b
a
d
d c
c
a b
a c
If weighted, store weights also in
adjacency lists.
Dr. AMIT KUMAR @JUET
Storage Requirement
• For directed graphs:
– Sum of lengths of all adj. lists is
out-degree(v) = |E|
vV
– Total storage: (V+E)
• For undirected graphs:
– Sum of lengths of all adj. lists is
degree(v) = 2|E|
vV
– Total storage: (V+E)
No. of edges leaving v
No. of edges incident on v. Edge (u,v) is incident
on vertices u and v.
Dr. AMIT KUMAR @JUET
Pros and Cons: adj list
• Pros
– Space-efficient, when a graph is sparse.
– Can be modified to support many graph variants.
• Cons
– Determining if an edge (u,v) G is not efficient.
• Have to search in u’s adjacency list. (degree(u)) time.
• (V) in the worst case.
Dr. AMIT KUMAR @JUET
Adjacency Matrix
• |V|  |V| matrix A.
• Number vertices from 1 to |V| in some arbitrary
manner.
• A is then given by:


 

otherwise0
),(if1
],[
Eji
ajiA ij
a
dc
b
1 2
3 4
1 2 3 4
1 0 1 1 1
2 0 0 1 0
3 0 0 0 1
4 0 0 0 0
a
dc
b
1 2
3 4
1 2 3 4
1 0 1 1 1
2 1 0 1 0
3 1 1 0 1
4 1 0 1 0
A = AT for undirected graphs.
Dr. AMIT KUMAR @JUET
Space and Time
• Space: (V2).
– Not memory efficient for large graphs.
• Time: to list all vertices adjacent to u: (V).
• Time: to determine if (u, v)  E: (1).
• Can store weights instead of bits for weighted graph.
Dr. AMIT KUMAR @JUET
Graph-searching Algorithms
• Searching a graph:
– Systematically follow the edges of a graph
to visit the vertices of the graph.
• Used to discover the structure of a graph.
• Standard graph-searching algorithms.
– Breadth-first Search (BFS).
– Depth-first Search (DFS).
Dr. AMIT KUMAR @JUET
Breadth-first Search
• Input: Graph G = (V, E), either directed or undirected,
and source vertex s  V.
• Output:
– d[v] = distance (smallest # of edges, or shortest path) from s to
v, for all v  V. d[v] =  if v is not reachable from s.
– [v] = u such that (u, v) is last edge on shortest path s v.
• u is v’s predecessor.
– Builds breadth-first tree with root s that contains all reachable
vertices.
Definitions:
Path between vertices u and v: Sequence of vertices (v1, v2, …, vk) such that
u=v1 and v =vk, and (vi,vi+1)  E, for all 1 i  k-1.
Length of the path: Number of edges in the path.
Path is simple if no vertex is repeated.
Error!
Dr. AMIT KUMAR @JUET
Breadth-first Search
• Expands the frontier between discovered and
undiscovered vertices uniformly across the breadth of
the frontier.
– A vertex is “discovered” the first time it is encountered during
the search.
– A vertex is “finished” if all vertices adjacent to it have been
discovered.
• Colors the vertices to keep track of progress.
– White – Undiscovered.
– Gray – Discovered but not finished.
– Black – Finished.
• Colors are required only to reason about the algorithm. Can be
implemented without colors.
Dr. AMIT KUMAR @JUET
BFS(G,s)
1. for each vertex u in V[G] – {s}
2 do color[u]  white
3 d[u]  
4 [u]  nil
5 color[s]  gray
6 d[s]  0
7 [s]  nil
8 Q  
9 enqueue(Q,s)
10 while Q  
11 do u  dequeue(Q)
12 for each v in Adj[u]
13 do if color[v] = white
14 then color[v]  gray
15 d[v]  d[u] + 1
16 [v]  u
17 enqueue(Q,v)
18 color[u]  black
white: undiscovered
gray: discovered
black: finished
Q: a queue of discovered
vertices
color[v]: color of v
d[v]: distance from s to v
[u]: predecessor of v
Example: animation.
Dr. AMIT KUMAR @JUET
Example (BFS)
 0
  
 

r s t u
v w x y
Q: s
0
Dr. AMIT KUMAR @JUET
Example (BFS)
1 0
1  
 

r s t u
v w x y
Q: w r
1 1
Dr. AMIT KUMAR @JUET
Example (BFS)
1 0
1 2 
2 

r s t u
v w x y
Q: r t x
1 2 2
Dr. AMIT KUMAR @JUET
Example (BFS)
1 0
1 2 
2 
2
r s t u
v w x y
Q: t x v
2 2 2
Dr. AMIT KUMAR @JUET
Example (BFS)
1 0
1 2 
2 3
2
r s t u
v w x y
Q: x v u
2 2 3
Dr. AMIT KUMAR @JUET
Example (BFS)
1 0
1 2 3
2 3
2
r s t u
v w x y
Q: v u y
2 3 3
Dr. AMIT KUMAR @JUET
Example (BFS)
1 0
1 2 3
2 3
2
r s t u
v w x y
Q: u y
3 3
Dr. AMIT KUMAR @JUET
Example (BFS)
1 0
1 2 3
2 3
2
r s t u
v w x y
Q: y
3
Dr. AMIT KUMAR @JUET
Example (BFS)
1 0
1 2 3
2 3
2
r s t u
v w x y
Q: 
Dr. AMIT KUMAR @JUET
Example (BFS)
1 0
1 2 3
2 3
2
r s t u
v w x y
BF Tree
Dr. AMIT KUMAR @JUET
Analysis of BFS
• Initialization takes O(V).
• Traversal Loop
– After initialization, each vertex is enqueued and dequeued at
most once, and each operation takes O(1). So, total time for
queuing is O(V).
– The adjacency list of each vertex is scanned at most once. The
sum of lengths of all adjacency lists is (E).
• Summing up over all vertices => total running time of BFS
is O(V+E), linear in the size of the adjacency list
representation of graph.
• Correctness Proof
– We omit for BFS and DFS.
– Will do for later algorithms.
Dr. AMIT KUMAR @JUET
Breadth-first Tree
• For a graph G = (V, E) with source s, the predecessor
subgraph of G is G = (V , E) where
– V ={vV : [v]  NIL}{s}
– E ={([v],v)E : v  V - {s}}
• The predecessor subgraph G is a breadth-first tree if:
– V consists of the vertices reachable from s and
– for all vV , there is a unique simple path from s to v in G
that is also a shortest path from s to v in G.
• The edges in E are called tree edges.
|E | = |V | - 1.
Dr. AMIT KUMAR @JUET
Depth-first Search (DFS)
• Explore edges out of the most recently discovered
vertex v.
• When all edges of v have been explored, backtrack to
explore other edges leaving the vertex from which v
was discovered (its predecessor).
• “Search as deep as possible first.”
• Continue until all vertices reachable from the original
source are discovered.
• If any undiscovered vertices remain, then one of them
is chosen as a new source and search is repeated from
that source.
Dr. AMIT KUMAR @JUET
Depth-first Search
• Input: G = (V, E), directed or undirected. No source
vertex given!
• Output:
– 2 timestamps on each vertex. Integers between 1 and 2|V|.
• d[v] = discovery time (v turns from white to gray)
• f [v] = finishing time (v turns from gray to black)
– [v] : predecessor of v = u, such that v was discovered during
the scan of u’s adjacency list.
• Uses the same coloring scheme for vertices as BFS.
Dr. AMIT KUMAR @JUET
Pseudo-code
DFS(G)
1. for each vertex u  V[G]
2. do color[u]  white
3. [u]  NIL
4. time  0
5. for each vertex u  V[G]
6. do if color[u] = white
7. then DFS-Visit(u)
Uses a global timestamp time.
DFS-Visit(u)
1. color[u]  GRAY  White vertex u
has been discovered
2. time  time + 1
3. d[u]  time
4. for each v  Adj[u]
5. do if color[v] = WHITE
6. then [v]  u
7. DFS-Visit(v)
8. color[u]  BLACK  Blacken u;
it is finished.
9. f[u]  time  time + 1
Dr. AMIT KUMAR @JUET
Example (DFS)
1/
u v w
x y z
Dr. AMIT KUMAR @JUET
Example (DFS)
1/ 2/
u v w
x y z
Dr. AMIT KUMAR @JUET
Example (DFS)
1/
3/
2/
u v w
x y z
Dr. AMIT KUMAR @JUET
Example (DFS)
1/
4/ 3/
2/
u v w
x y z
Dr. AMIT KUMAR @JUET
Example (DFS)
1/
4/ 3/
2/
u v w
x y z
B
Dr. AMIT KUMAR @JUET
Example (DFS)
1/
4/5 3/
2/
u v w
x y z
B
Dr. AMIT KUMAR @JUET
Example (DFS)
1/
4/5 3/6
2/
u v w
x y z
B
Dr. AMIT KUMAR @JUET
Example (DFS)
1/
4/5 3/6
2/7
u v w
x y z
B
Dr. AMIT KUMAR @JUET
Example (DFS)
1/
4/5 3/6
2/7
u v w
x y z
BF
Dr. AMIT KUMAR @JUET
Example (DFS)
1/8
4/5 3/6
2/7
u v w
x y z
BF
Dr. AMIT KUMAR @JUET
Example (DFS)
1/8
4/5 3/6
2/7 9/
u v w
x y z
BF
Dr. AMIT KUMAR @JUET
Example (DFS)
1/8
4/5 3/6
2/7 9/
u v w
x y z
BF C
Dr. AMIT KUMAR @JUET
Example (DFS)
1/8
4/5 3/6 10/
2/7 9/
u v w
x y z
BF C
Dr. AMIT KUMAR @JUET
Example (DFS)
1/8
4/5 3/6 10/
2/7 9/
u v w
x y z
BF C
B
Dr. AMIT KUMAR @JUET
Example (DFS)
1/8
4/5 3/6 10/11
2/7 9/
u v w
x y z
BF C
B
Dr. AMIT KUMAR @JUET
Example (DFS)
1/8
4/5 3/6 10/11
2/7 9/12
u v w
x y z
BF C
B
Dr. AMIT KUMAR @JUET
Analysis of DFS
• Loops on lines 1-2 & 5-7 take (V) time, excluding time
to execute DFS-Visit.
• DFS-Visit is called once for each white vertex vV when
it’s painted gray the first time. Lines 3-6 of DFS-Visit is
executed |Adj[v]| times. The total cost of executing
DFS-Visit is vV|Adj[v]| = (E)
• Total running time of DFS is (V+E).
Dr. AMIT KUMAR @JUET
Depth-First Trees
• Predecessor subgraph defined slightly different from
that of BFS.
• The predecessor subgraph of DFS is G = (V, E) where
E ={([v],v) : v  V and [v]  NIL}.
– How does it differ from that of BFS?
– The predecessor subgraph G forms a depth-first forest
composed of several depth-first trees. The edges in E are
called tree edges.
Definition:
Forest: An acyclic graph G that may be disconnected.
Dr. AMIT KUMAR @JUET
Classification of Edges
• Tree edge: in the depth-first forest. Found by exploring
(u, v).
• Back edge: (u, v), where u is a descendant of v (in the
depth-first tree).
• Forward edge: (u, v), where v is a descendant of u, but
not a tree edge.
• Cross edge: any other edge. Can go between vertices in
same depth-first tree or in different depth-first trees.
Theorem:
In DFS of an undirected graph, we get only tree and back edges.
No forward or cross edges.
Dr. AMIT KUMAR @JUET

More Related Content

What's hot

Shortest Path in Graph
Shortest Path in GraphShortest Path in Graph
Shortest Path in Graph
Dr Sandeep Kumar Poonia
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
Shuvongkor Barman
 
Topological Sorting (Decrease and Conquer)
Topological Sorting (Decrease and Conquer)Topological Sorting (Decrease and Conquer)
Topological Sorting (Decrease and Conquer)
Gem WeBlog
 
Graph
GraphGraph
Graph
ssnetvnr
 
Classification in data mining
Classification in data mining Classification in data mining
Classification in data mining
Sulman Ahmed
 
Relational algebra ppt
Relational algebra pptRelational algebra ppt
Relational algebra ppt
GirdharRatne
 
Graphs - Discrete Math
Graphs - Discrete MathGraphs - Discrete Math
Graphs - Discrete Math
Sikder Tahsin Al-Amin
 
Slides Chapter10.1 10.2
Slides Chapter10.1 10.2Slides Chapter10.1 10.2
Slides Chapter10.1 10.2showslidedump
 
Graph Theory
Graph TheoryGraph Theory
Graph Theory
Ehsan Hamzei
 
Bfs and dfs in data structure
Bfs and dfs in  data structure Bfs and dfs in  data structure
Bfs and dfs in data structure
Ankit Kumar Singh
 
Graph coloring using backtracking
Graph coloring using backtrackingGraph coloring using backtracking
Graph coloring using backtracking
shashidharPapishetty
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
sandeep54552
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
Nv Thejaswini
 
Prim's algorithm
Prim's algorithmPrim's algorithm
Prim's algorithm
Pankaj Thakur
 
Greedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack ProblemGreedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack Problem
Madhu Bala
 
GRAPH COLORING AND ITS APPLICATIONS
GRAPH COLORING AND ITS APPLICATIONSGRAPH COLORING AND ITS APPLICATIONS
GRAPH COLORING AND ITS APPLICATIONS
Manojit Chakraborty
 
Graph coloring problem
Graph coloring problemGraph coloring problem
Graph coloring problem
V.V.Vanniaperumal College for Women
 
Bellman ford Algorithm
Bellman ford AlgorithmBellman ford Algorithm
Bellman ford Algorithmtaimurkhan803
 
ambiguity grammar.pdf
ambiguity grammar.pdfambiguity grammar.pdf
ambiguity grammar.pdf
BilalWarraich15
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
DEEPIKA T
 

What's hot (20)

Shortest Path in Graph
Shortest Path in GraphShortest Path in Graph
Shortest Path in Graph
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
 
Topological Sorting (Decrease and Conquer)
Topological Sorting (Decrease and Conquer)Topological Sorting (Decrease and Conquer)
Topological Sorting (Decrease and Conquer)
 
Graph
GraphGraph
Graph
 
Classification in data mining
Classification in data mining Classification in data mining
Classification in data mining
 
Relational algebra ppt
Relational algebra pptRelational algebra ppt
Relational algebra ppt
 
Graphs - Discrete Math
Graphs - Discrete MathGraphs - Discrete Math
Graphs - Discrete Math
 
Slides Chapter10.1 10.2
Slides Chapter10.1 10.2Slides Chapter10.1 10.2
Slides Chapter10.1 10.2
 
Graph Theory
Graph TheoryGraph Theory
Graph Theory
 
Bfs and dfs in data structure
Bfs and dfs in  data structure Bfs and dfs in  data structure
Bfs and dfs in data structure
 
Graph coloring using backtracking
Graph coloring using backtrackingGraph coloring using backtracking
Graph coloring using backtracking
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
 
Prim's algorithm
Prim's algorithmPrim's algorithm
Prim's algorithm
 
Greedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack ProblemGreedy Algorithm - Knapsack Problem
Greedy Algorithm - Knapsack Problem
 
GRAPH COLORING AND ITS APPLICATIONS
GRAPH COLORING AND ITS APPLICATIONSGRAPH COLORING AND ITS APPLICATIONS
GRAPH COLORING AND ITS APPLICATIONS
 
Graph coloring problem
Graph coloring problemGraph coloring problem
Graph coloring problem
 
Bellman ford Algorithm
Bellman ford AlgorithmBellman ford Algorithm
Bellman ford Algorithm
 
ambiguity grammar.pdf
ambiguity grammar.pdfambiguity grammar.pdf
ambiguity grammar.pdf
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
 

Similar to Bfs dfs

B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in india
Edhole.com
 
19-graph1 (1).ppt
19-graph1 (1).ppt19-graph1 (1).ppt
19-graph1 (1).ppt
Himajanaidu2
 
topological_sort_strongly Connected Components
topological_sort_strongly Connected Componentstopological_sort_strongly Connected Components
topological_sort_strongly Connected Components
JahidulIslam47153
 
Graph representation
Graph representationGraph representation
Graph representation
Amit Kumar Rathi
 
BFS
BFSBFS
Graph Traversal Algorithm
Graph Traversal AlgorithmGraph Traversal Algorithm
Graph Traversal Algorithm
jyothimonc
 
Elementary Graph Algo.ppt
Elementary Graph Algo.pptElementary Graph Algo.ppt
Elementary Graph Algo.ppt
SazidHossain9
 
Shortest path algorithms
Shortest path algorithmsShortest path algorithms
Shortest path algorithms
Amit Kumar Rathi
 
BFS, Breadth first search | Search Traversal Algorithm
BFS, Breadth first search | Search Traversal AlgorithmBFS, Breadth first search | Search Traversal Algorithm
BFS, Breadth first search | Search Traversal Algorithm
MSA Technosoft
 
Chapter 23 aoa
Chapter 23 aoaChapter 23 aoa
Chapter 23 aoa
Hanif Durad
 
Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Naor Ami
 
lecture 18
lecture 18lecture 18
lecture 18sajinsc
 
LEC 1.pptx
LEC 1.pptxLEC 1.pptx
LEC 1.pptx
ssuserc1e786
 
Graph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxGraph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptx
bashirabdullah789
 
Shortest Paths Part 2: Negative Weights and All-pairs
Shortest Paths Part 2: Negative Weights and All-pairsShortest Paths Part 2: Negative Weights and All-pairs
Shortest Paths Part 2: Negative Weights and All-pairs
Benjamin Sach
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
Ruchika Sinha
 
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.ppt
TalhaFarooqui12
 
Topological sorting
Topological sortingTopological sorting
Topological sorting
Amit Kumar Rathi
 

Similar to Bfs dfs (20)

B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in india
 
19-graph1 (1).ppt
19-graph1 (1).ppt19-graph1 (1).ppt
19-graph1 (1).ppt
 
topological_sort_strongly Connected Components
topological_sort_strongly Connected Componentstopological_sort_strongly Connected Components
topological_sort_strongly Connected Components
 
Graph representation
Graph representationGraph representation
Graph representation
 
BFS
BFSBFS
BFS
 
Graph Traversal Algorithm
Graph Traversal AlgorithmGraph Traversal Algorithm
Graph Traversal Algorithm
 
Elementary Graph Algo.ppt
Elementary Graph Algo.pptElementary Graph Algo.ppt
Elementary Graph Algo.ppt
 
Shortest path algorithms
Shortest path algorithmsShortest path algorithms
Shortest path algorithms
 
BFS, Breadth first search | Search Traversal Algorithm
BFS, Breadth first search | Search Traversal AlgorithmBFS, Breadth first search | Search Traversal Algorithm
BFS, Breadth first search | Search Traversal Algorithm
 
Chapter 23 aoa
Chapter 23 aoaChapter 23 aoa
Chapter 23 aoa
 
Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14Inroduction_To_Algorithms_Lect14
Inroduction_To_Algorithms_Lect14
 
lecture 18
lecture 18lecture 18
lecture 18
 
LEC 1.pptx
LEC 1.pptxLEC 1.pptx
LEC 1.pptx
 
Graph theory
Graph theoryGraph theory
Graph theory
 
Graph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxGraph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptx
 
Shortest Paths Part 2: Negative Weights and All-pairs
Shortest Paths Part 2: Negative Weights and All-pairsShortest Paths Part 2: Negative Weights and All-pairs
Shortest Paths Part 2: Negative Weights and All-pairs
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 
Bfs dfs
Bfs dfsBfs dfs
Bfs dfs
 
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.ppt
 
Topological sorting
Topological sortingTopological sorting
Topological sorting
 

More from Amit Kumar Rathi

Hybrid Systems using Fuzzy, NN and GA (Soft Computing)
Hybrid Systems using Fuzzy, NN and GA (Soft Computing)Hybrid Systems using Fuzzy, NN and GA (Soft Computing)
Hybrid Systems using Fuzzy, NN and GA (Soft Computing)
Amit Kumar Rathi
 
Fundamentals of Genetic Algorithms (Soft Computing)
Fundamentals of Genetic Algorithms (Soft Computing)Fundamentals of Genetic Algorithms (Soft Computing)
Fundamentals of Genetic Algorithms (Soft Computing)
Amit Kumar Rathi
 
Fuzzy Systems by using fuzzy set (Soft Computing)
Fuzzy Systems by using fuzzy set (Soft Computing)Fuzzy Systems by using fuzzy set (Soft Computing)
Fuzzy Systems by using fuzzy set (Soft Computing)
Amit Kumar Rathi
 
Fuzzy Set Theory and Classical Set Theory (Soft Computing)
Fuzzy Set Theory and Classical Set Theory (Soft Computing)Fuzzy Set Theory and Classical Set Theory (Soft Computing)
Fuzzy Set Theory and Classical Set Theory (Soft Computing)
Amit Kumar Rathi
 
Associative Memory using NN (Soft Computing)
Associative Memory using NN (Soft Computing)Associative Memory using NN (Soft Computing)
Associative Memory using NN (Soft Computing)
Amit Kumar Rathi
 
Back Propagation Network (Soft Computing)
Back Propagation Network (Soft Computing)Back Propagation Network (Soft Computing)
Back Propagation Network (Soft Computing)
Amit Kumar Rathi
 
Fundamentals of Neural Network (Soft Computing)
Fundamentals of Neural Network (Soft Computing)Fundamentals of Neural Network (Soft Computing)
Fundamentals of Neural Network (Soft Computing)
Amit Kumar Rathi
 
Introduction to Soft Computing (intro to the building blocks of SC)
Introduction to Soft Computing (intro to the building blocks of SC)Introduction to Soft Computing (intro to the building blocks of SC)
Introduction to Soft Computing (intro to the building blocks of SC)
Amit Kumar Rathi
 
String matching, naive,
String matching, naive,String matching, naive,
String matching, naive,
Amit Kumar Rathi
 
Sccd and topological sorting
Sccd and topological sortingSccd and topological sorting
Sccd and topological sorting
Amit Kumar Rathi
 
Red black trees
Red black treesRed black trees
Red black trees
Amit Kumar Rathi
 
Recurrence and master theorem
Recurrence and master theoremRecurrence and master theorem
Recurrence and master theorem
Amit Kumar Rathi
 
Rabin karp string matcher
Rabin karp string matcherRabin karp string matcher
Rabin karp string matcher
Amit Kumar Rathi
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
Amit Kumar Rathi
 
Merge sort analysis
Merge sort analysisMerge sort analysis
Merge sort analysis
Amit Kumar Rathi
 
Loop invarient
Loop invarientLoop invarient
Loop invarient
Amit Kumar Rathi
 
Linear sort
Linear sortLinear sort
Linear sort
Amit Kumar Rathi
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
Amit Kumar Rathi
 
Greedy algorithm activity selection fractional
Greedy algorithm activity selection fractionalGreedy algorithm activity selection fractional
Greedy algorithm activity selection fractional
Amit Kumar Rathi
 
Fundamentals of algorithms
Fundamentals of algorithmsFundamentals of algorithms
Fundamentals of algorithms
Amit Kumar Rathi
 

More from Amit Kumar Rathi (20)

Hybrid Systems using Fuzzy, NN and GA (Soft Computing)
Hybrid Systems using Fuzzy, NN and GA (Soft Computing)Hybrid Systems using Fuzzy, NN and GA (Soft Computing)
Hybrid Systems using Fuzzy, NN and GA (Soft Computing)
 
Fundamentals of Genetic Algorithms (Soft Computing)
Fundamentals of Genetic Algorithms (Soft Computing)Fundamentals of Genetic Algorithms (Soft Computing)
Fundamentals of Genetic Algorithms (Soft Computing)
 
Fuzzy Systems by using fuzzy set (Soft Computing)
Fuzzy Systems by using fuzzy set (Soft Computing)Fuzzy Systems by using fuzzy set (Soft Computing)
Fuzzy Systems by using fuzzy set (Soft Computing)
 
Fuzzy Set Theory and Classical Set Theory (Soft Computing)
Fuzzy Set Theory and Classical Set Theory (Soft Computing)Fuzzy Set Theory and Classical Set Theory (Soft Computing)
Fuzzy Set Theory and Classical Set Theory (Soft Computing)
 
Associative Memory using NN (Soft Computing)
Associative Memory using NN (Soft Computing)Associative Memory using NN (Soft Computing)
Associative Memory using NN (Soft Computing)
 
Back Propagation Network (Soft Computing)
Back Propagation Network (Soft Computing)Back Propagation Network (Soft Computing)
Back Propagation Network (Soft Computing)
 
Fundamentals of Neural Network (Soft Computing)
Fundamentals of Neural Network (Soft Computing)Fundamentals of Neural Network (Soft Computing)
Fundamentals of Neural Network (Soft Computing)
 
Introduction to Soft Computing (intro to the building blocks of SC)
Introduction to Soft Computing (intro to the building blocks of SC)Introduction to Soft Computing (intro to the building blocks of SC)
Introduction to Soft Computing (intro to the building blocks of SC)
 
String matching, naive,
String matching, naive,String matching, naive,
String matching, naive,
 
Sccd and topological sorting
Sccd and topological sortingSccd and topological sorting
Sccd and topological sorting
 
Red black trees
Red black treesRed black trees
Red black trees
 
Recurrence and master theorem
Recurrence and master theoremRecurrence and master theorem
Recurrence and master theorem
 
Rabin karp string matcher
Rabin karp string matcherRabin karp string matcher
Rabin karp string matcher
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
 
Merge sort analysis
Merge sort analysisMerge sort analysis
Merge sort analysis
 
Loop invarient
Loop invarientLoop invarient
Loop invarient
 
Linear sort
Linear sortLinear sort
Linear sort
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
Greedy algorithm activity selection fractional
Greedy algorithm activity selection fractionalGreedy algorithm activity selection fractional
Greedy algorithm activity selection fractional
 
Fundamentals of algorithms
Fundamentals of algorithmsFundamentals of algorithms
Fundamentals of algorithms
 

Recently uploaded

ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 

Recently uploaded (20)

ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 

Bfs dfs

  • 2. Graphs • Graph G = (V, E) – V = set of vertices – E = set of edges  (VV) • Types of graphs – Undirected: edge (u, v) = (v, u); for all v, (v, v)  E (No self loops.) – Directed: (u, v) is edge from u to v, denoted as u  v. Self loops are allowed. – Weighted: each edge has an associated weight, given by a weight function w : E  R. – Dense: |E|  |V|2. – Sparse: |E| << |V|2. • |E| = O(|V|2) Dr. AMIT KUMAR @JUET
  • 3. Graphs • If (u, v)  E, then vertex v is adjacent to vertex u. • Adjacency relationship is: – Symmetric if G is undirected. – Not necessarily so if G is directed. • If G is connected: – There is a path between every pair of vertices. – |E|  |V| – 1. – Furthermore, if |E| = |V| – 1, then G is a tree. • Other definitions in Appendix B (B.4 and B.5) as needed. Dr. AMIT KUMAR @JUET
  • 4. Representation of Graphs • Two standard ways. – Adjacency Lists. – Adjacency Matrix. a dc b a b c d b a d d c c a b a c a dc b 1 2 3 4 1 2 3 4 1 0 1 1 1 2 1 0 1 0 3 1 1 0 1 4 1 0 1 0 Dr. AMIT KUMAR @JUET
  • 5. Adjacency Lists • Consists of an array Adj of |V| lists. • One list per vertex. • For u  V, Adj[u] consists of all vertices adjacent to u. a dc b a b c d b c d d c a dc b a b c d b a d d c c a b a c If weighted, store weights also in adjacency lists. Dr. AMIT KUMAR @JUET
  • 6. Storage Requirement • For directed graphs: – Sum of lengths of all adj. lists is out-degree(v) = |E| vV – Total storage: (V+E) • For undirected graphs: – Sum of lengths of all adj. lists is degree(v) = 2|E| vV – Total storage: (V+E) No. of edges leaving v No. of edges incident on v. Edge (u,v) is incident on vertices u and v. Dr. AMIT KUMAR @JUET
  • 7. Pros and Cons: adj list • Pros – Space-efficient, when a graph is sparse. – Can be modified to support many graph variants. • Cons – Determining if an edge (u,v) G is not efficient. • Have to search in u’s adjacency list. (degree(u)) time. • (V) in the worst case. Dr. AMIT KUMAR @JUET
  • 8. Adjacency Matrix • |V|  |V| matrix A. • Number vertices from 1 to |V| in some arbitrary manner. • A is then given by:      otherwise0 ),(if1 ],[ Eji ajiA ij a dc b 1 2 3 4 1 2 3 4 1 0 1 1 1 2 0 0 1 0 3 0 0 0 1 4 0 0 0 0 a dc b 1 2 3 4 1 2 3 4 1 0 1 1 1 2 1 0 1 0 3 1 1 0 1 4 1 0 1 0 A = AT for undirected graphs. Dr. AMIT KUMAR @JUET
  • 9. Space and Time • Space: (V2). – Not memory efficient for large graphs. • Time: to list all vertices adjacent to u: (V). • Time: to determine if (u, v)  E: (1). • Can store weights instead of bits for weighted graph. Dr. AMIT KUMAR @JUET
  • 10. Graph-searching Algorithms • Searching a graph: – Systematically follow the edges of a graph to visit the vertices of the graph. • Used to discover the structure of a graph. • Standard graph-searching algorithms. – Breadth-first Search (BFS). – Depth-first Search (DFS). Dr. AMIT KUMAR @JUET
  • 11. Breadth-first Search • Input: Graph G = (V, E), either directed or undirected, and source vertex s  V. • Output: – d[v] = distance (smallest # of edges, or shortest path) from s to v, for all v  V. d[v] =  if v is not reachable from s. – [v] = u such that (u, v) is last edge on shortest path s v. • u is v’s predecessor. – Builds breadth-first tree with root s that contains all reachable vertices. Definitions: Path between vertices u and v: Sequence of vertices (v1, v2, …, vk) such that u=v1 and v =vk, and (vi,vi+1)  E, for all 1 i  k-1. Length of the path: Number of edges in the path. Path is simple if no vertex is repeated. Error! Dr. AMIT KUMAR @JUET
  • 12. Breadth-first Search • Expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. – A vertex is “discovered” the first time it is encountered during the search. – A vertex is “finished” if all vertices adjacent to it have been discovered. • Colors the vertices to keep track of progress. – White – Undiscovered. – Gray – Discovered but not finished. – Black – Finished. • Colors are required only to reason about the algorithm. Can be implemented without colors. Dr. AMIT KUMAR @JUET
  • 13. BFS(G,s) 1. for each vertex u in V[G] – {s} 2 do color[u]  white 3 d[u]   4 [u]  nil 5 color[s]  gray 6 d[s]  0 7 [s]  nil 8 Q   9 enqueue(Q,s) 10 while Q   11 do u  dequeue(Q) 12 for each v in Adj[u] 13 do if color[v] = white 14 then color[v]  gray 15 d[v]  d[u] + 1 16 [v]  u 17 enqueue(Q,v) 18 color[u]  black white: undiscovered gray: discovered black: finished Q: a queue of discovered vertices color[v]: color of v d[v]: distance from s to v [u]: predecessor of v Example: animation. Dr. AMIT KUMAR @JUET
  • 14. Example (BFS)  0       r s t u v w x y Q: s 0 Dr. AMIT KUMAR @JUET
  • 15. Example (BFS) 1 0 1      r s t u v w x y Q: w r 1 1 Dr. AMIT KUMAR @JUET
  • 16. Example (BFS) 1 0 1 2  2   r s t u v w x y Q: r t x 1 2 2 Dr. AMIT KUMAR @JUET
  • 17. Example (BFS) 1 0 1 2  2  2 r s t u v w x y Q: t x v 2 2 2 Dr. AMIT KUMAR @JUET
  • 18. Example (BFS) 1 0 1 2  2 3 2 r s t u v w x y Q: x v u 2 2 3 Dr. AMIT KUMAR @JUET
  • 19. Example (BFS) 1 0 1 2 3 2 3 2 r s t u v w x y Q: v u y 2 3 3 Dr. AMIT KUMAR @JUET
  • 20. Example (BFS) 1 0 1 2 3 2 3 2 r s t u v w x y Q: u y 3 3 Dr. AMIT KUMAR @JUET
  • 21. Example (BFS) 1 0 1 2 3 2 3 2 r s t u v w x y Q: y 3 Dr. AMIT KUMAR @JUET
  • 22. Example (BFS) 1 0 1 2 3 2 3 2 r s t u v w x y Q:  Dr. AMIT KUMAR @JUET
  • 23. Example (BFS) 1 0 1 2 3 2 3 2 r s t u v w x y BF Tree Dr. AMIT KUMAR @JUET
  • 24. Analysis of BFS • Initialization takes O(V). • Traversal Loop – After initialization, each vertex is enqueued and dequeued at most once, and each operation takes O(1). So, total time for queuing is O(V). – The adjacency list of each vertex is scanned at most once. The sum of lengths of all adjacency lists is (E). • Summing up over all vertices => total running time of BFS is O(V+E), linear in the size of the adjacency list representation of graph. • Correctness Proof – We omit for BFS and DFS. – Will do for later algorithms. Dr. AMIT KUMAR @JUET
  • 25. Breadth-first Tree • For a graph G = (V, E) with source s, the predecessor subgraph of G is G = (V , E) where – V ={vV : [v]  NIL}{s} – E ={([v],v)E : v  V - {s}} • The predecessor subgraph G is a breadth-first tree if: – V consists of the vertices reachable from s and – for all vV , there is a unique simple path from s to v in G that is also a shortest path from s to v in G. • The edges in E are called tree edges. |E | = |V | - 1. Dr. AMIT KUMAR @JUET
  • 26. Depth-first Search (DFS) • Explore edges out of the most recently discovered vertex v. • When all edges of v have been explored, backtrack to explore other edges leaving the vertex from which v was discovered (its predecessor). • “Search as deep as possible first.” • Continue until all vertices reachable from the original source are discovered. • If any undiscovered vertices remain, then one of them is chosen as a new source and search is repeated from that source. Dr. AMIT KUMAR @JUET
  • 27. Depth-first Search • Input: G = (V, E), directed or undirected. No source vertex given! • Output: – 2 timestamps on each vertex. Integers between 1 and 2|V|. • d[v] = discovery time (v turns from white to gray) • f [v] = finishing time (v turns from gray to black) – [v] : predecessor of v = u, such that v was discovered during the scan of u’s adjacency list. • Uses the same coloring scheme for vertices as BFS. Dr. AMIT KUMAR @JUET
  • 28. Pseudo-code DFS(G) 1. for each vertex u  V[G] 2. do color[u]  white 3. [u]  NIL 4. time  0 5. for each vertex u  V[G] 6. do if color[u] = white 7. then DFS-Visit(u) Uses a global timestamp time. DFS-Visit(u) 1. color[u]  GRAY  White vertex u has been discovered 2. time  time + 1 3. d[u]  time 4. for each v  Adj[u] 5. do if color[v] = WHITE 6. then [v]  u 7. DFS-Visit(v) 8. color[u]  BLACK  Blacken u; it is finished. 9. f[u]  time  time + 1 Dr. AMIT KUMAR @JUET
  • 29. Example (DFS) 1/ u v w x y z Dr. AMIT KUMAR @JUET
  • 30. Example (DFS) 1/ 2/ u v w x y z Dr. AMIT KUMAR @JUET
  • 31. Example (DFS) 1/ 3/ 2/ u v w x y z Dr. AMIT KUMAR @JUET
  • 32. Example (DFS) 1/ 4/ 3/ 2/ u v w x y z Dr. AMIT KUMAR @JUET
  • 33. Example (DFS) 1/ 4/ 3/ 2/ u v w x y z B Dr. AMIT KUMAR @JUET
  • 34. Example (DFS) 1/ 4/5 3/ 2/ u v w x y z B Dr. AMIT KUMAR @JUET
  • 35. Example (DFS) 1/ 4/5 3/6 2/ u v w x y z B Dr. AMIT KUMAR @JUET
  • 36. Example (DFS) 1/ 4/5 3/6 2/7 u v w x y z B Dr. AMIT KUMAR @JUET
  • 37. Example (DFS) 1/ 4/5 3/6 2/7 u v w x y z BF Dr. AMIT KUMAR @JUET
  • 38. Example (DFS) 1/8 4/5 3/6 2/7 u v w x y z BF Dr. AMIT KUMAR @JUET
  • 39. Example (DFS) 1/8 4/5 3/6 2/7 9/ u v w x y z BF Dr. AMIT KUMAR @JUET
  • 40. Example (DFS) 1/8 4/5 3/6 2/7 9/ u v w x y z BF C Dr. AMIT KUMAR @JUET
  • 41. Example (DFS) 1/8 4/5 3/6 10/ 2/7 9/ u v w x y z BF C Dr. AMIT KUMAR @JUET
  • 42. Example (DFS) 1/8 4/5 3/6 10/ 2/7 9/ u v w x y z BF C B Dr. AMIT KUMAR @JUET
  • 43. Example (DFS) 1/8 4/5 3/6 10/11 2/7 9/ u v w x y z BF C B Dr. AMIT KUMAR @JUET
  • 44. Example (DFS) 1/8 4/5 3/6 10/11 2/7 9/12 u v w x y z BF C B Dr. AMIT KUMAR @JUET
  • 45. Analysis of DFS • Loops on lines 1-2 & 5-7 take (V) time, excluding time to execute DFS-Visit. • DFS-Visit is called once for each white vertex vV when it’s painted gray the first time. Lines 3-6 of DFS-Visit is executed |Adj[v]| times. The total cost of executing DFS-Visit is vV|Adj[v]| = (E) • Total running time of DFS is (V+E). Dr. AMIT KUMAR @JUET
  • 46. Depth-First Trees • Predecessor subgraph defined slightly different from that of BFS. • The predecessor subgraph of DFS is G = (V, E) where E ={([v],v) : v  V and [v]  NIL}. – How does it differ from that of BFS? – The predecessor subgraph G forms a depth-first forest composed of several depth-first trees. The edges in E are called tree edges. Definition: Forest: An acyclic graph G that may be disconnected. Dr. AMIT KUMAR @JUET
  • 47. Classification of Edges • Tree edge: in the depth-first forest. Found by exploring (u, v). • Back edge: (u, v), where u is a descendant of v (in the depth-first tree). • Forward edge: (u, v), where v is a descendant of u, but not a tree edge. • Cross edge: any other edge. Can go between vertices in same depth-first tree or in different depth-first trees. Theorem: In DFS of an undirected graph, we get only tree and back edges. No forward or cross edges. Dr. AMIT KUMAR @JUET