SlideShare a Scribd company logo
1 of 35
Graph Traversal
Depth-First Search
• Using Stack
Breadth-First Search
• Using Queue
Overview
• Goal
– To systematically visit the nodes of a graph
• A tree is a directed, acyclic, graph (DAG)
• If the graph is a tree,
– DFS is exhibited by preorder, postorder, and
(for binary trees) inorder traversals
– BFS is exhibited by level-order traversal
Depth-First Search
// recursive, preorder, depth-first search
void dfs (Node v) {
if (v == null)
return;
if (v not yet visited)
visit&mark(v); // visit node before adjacent nodes
for (each w adjacent to v)
if (w has not yet been visited)
dfs(w);
} // dfs
Example
0
7
1
5
4
3
2
6
Policy: Visit adjacent nodes in increasing index order
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0 3 2 7 6 4
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5
Push 5
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5
Pop/Visit/Mark 5
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5
1
2
Push 2, Push 1
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1
2
Pop/Visit/Mark 1
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1
0
4
2
Push 4, Push 0
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0
4
2
Pop/Visit/Mark 0
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0
3
7
4
2
Push 7, Push 3
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0 3
7
4
2
Pop/Visit/Mark 3
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0 3
7
4
2
2 is already in stack
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0 3 7
7
4
2
Pop/Mark/Visit 7
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0 3 7
6
4
2
Push 6
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0 3 7 6
4
2
Pop/Mark/Visit 6
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0 3 7 6 4
2
Pop/Mark/Visit 4
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0 3 7 6 4 2
Pop/Mark/Visit 2
DFS: Start with Node 5
0
7
1
5
4
3
2
6
5 1 0 3 7 6 4 2
Done
Breadth-first Search
• Ripples in a pond
• Visit designated node
• Then visited unvisited nodes a distance i
away, where i = 1, 2, 3, etc.
• For nodes the same distance away, visit
nodes in systematic manner (eg. increasing
index order)
Breadth-First Search
// non-recursive, preorder, breadth-first search
void bfs (Node v) {
if (v == null)
return;
enqueue(v);
while (queue is not empty) {
dequeue(v);
if (v has not yet been visited)
mark&visit(v);
for (each w adjacent to v)
if (w has not yet been visited && has not been queued)
enqueue(w);
} // while
} // bfs
BFS: Start with Node 5
7
1
5
4
3
2
6
0
BFS: Start with Node 5
7
1
5
4
3
2
6
0
5
BFS: Node one-away
7
1
5
4
3
2
6
5
0
5 1 2
BFS: Visit 1 and add its adjacent
nodes
7
1
5
4
3
2
6
5 1
0
5 1 2 0 4
BFS: Visit 2 and add its adjacent
nodes
7
1
5
4
3
2
6
5 1 2
0
5 1 2 0 4
BFS: Visit 0 and add its adjacent
nodes
7
1
5
4
3
2
6
5 1 2 0
0
5 1 2 0 4 3 7
BFS: Visit 4 and add its adjacent
nodes
7
1
5
4
3
2
6
5 1 2 0 4
0
5 1 2 0 4 3 7
BFS: Visit 3 and add its adjacent
nodes
7
1
5
4
3
2
6
5 1 2 0 4 3
0
5 1 2 0 4 3 7
BFS: Visit 7 and add its adjacent
nodes
7
1
5
4
3
2
6
5 1 2 0 4 3 7
0
5 1 2 0 4 3 7 6
BFS: Visit 6 and add its adjacent
nodes
7
1
5
4
3
2
6
5 1 2 0 4 3 7 6
0
5 1 2 0 4 3 7 6
BFS Traversal Result
7
1
5
4
3
2
6
5 1 2 0 4 3 7 6
0
Applications of BFS
• Computing Distances: Given a source vertex x, compute the distance
of all vertices from x.
• Checking for cycles in a graph: Given an undirected graph G, report
whether there exists a cycle in the graph or not. (Note: won’t work for
directed graphs)
• Checking for bipartite graph: Given a graph, check whether it is
bipartite or not? A graph is said to be bipartite if there is a partition of
the vertex set V into two sets V1 and V2 such that if two vertices are
adjacent, either both are in V1 or both are in V2.
• Reachability: Given a graph G and vertices x and y, determine if there
exists a path from x to y.
Applications of DFS
• Computing Strongly Connected Components: A directed graph is
strongly connected if there exists a path from every vertex to every
other vertex. Trivial Algo: Perform DFS n times. Efficient Algo:
Single DFS.
• Checking for Biconnected Graph: A graph is biconnected if removal of
any vertex does not affect connectivity of the other vertices. Used to
test if network is robust to failure of certain nodes. A single DFS
traversal algorithm.
• Topological Ordering: Topological sorting for Directed Acyclic Graph
(DAG) is a linear ordering of vertices such that for every directed edge
(x, y), vertex x comes before y in the ordering

More Related Content

What's hot

Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
ghhgj jhgh
 
Graph representation
Graph representationGraph representation
Graph representation
Tech_MX
 

What's hot (20)

Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
 
Graphs bfs dfs
Graphs bfs dfsGraphs bfs dfs
Graphs bfs dfs
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
 
Breadth first search
Breadth first searchBreadth first search
Breadth first search
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
 
2.5 bfs & dfs 02
2.5 bfs & dfs 022.5 bfs & dfs 02
2.5 bfs & dfs 02
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
Depth firstsearchalgorithm
Depth firstsearchalgorithmDepth firstsearchalgorithm
Depth firstsearchalgorithm
 
Dijkstra s algorithm
Dijkstra s algorithmDijkstra s algorithm
Dijkstra s algorithm
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
 
A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithm
 
Application of dfs
Application of dfsApplication of dfs
Application of dfs
 
Red black tree
Red black treeRed black tree
Red black tree
 
Bellman Ford's Algorithm
Bellman Ford's AlgorithmBellman Ford's Algorithm
Bellman Ford's Algorithm
 
Graph representation
Graph representationGraph representation
Graph representation
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
Depth-First Search
Depth-First SearchDepth-First Search
Depth-First Search
 

Similar to Graph traversal-BFS & DFS

bfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptxbfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptx
saurabhpandey679381
 

Similar to Graph traversal-BFS & DFS (20)

BFS & DFS in Data Structure
BFS & DFS in Data StructureBFS & DFS in Data Structure
BFS & DFS in Data Structure
 
Breath first Search and Depth first search
Breath first Search and Depth first searchBreath first Search and Depth first search
Breath first Search and Depth first search
 
LAB7_FILS_DSA_graphs_datastructures.pptx
LAB7_FILS_DSA_graphs_datastructures.pptxLAB7_FILS_DSA_graphs_datastructures.pptx
LAB7_FILS_DSA_graphs_datastructures.pptx
 
kumattt).pptx
kumattt).pptxkumattt).pptx
kumattt).pptx
 
Analysis & design of algorithm
Analysis & design of algorithmAnalysis & design of algorithm
Analysis & design of algorithm
 
Graphs
GraphsGraphs
Graphs
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
Graph
GraphGraph
Graph
 
130210107039 2130702
130210107039 2130702130210107039 2130702
130210107039 2130702
 
bfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptxbfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptx
 
Bfs & dfs application
Bfs & dfs applicationBfs & dfs application
Bfs & dfs application
 
Depth first traversal(data structure algorithms)
Depth first traversal(data structure algorithms)Depth first traversal(data structure algorithms)
Depth first traversal(data structure algorithms)
 
U1 L5 DAA.pdf
U1 L5 DAA.pdfU1 L5 DAA.pdf
U1 L5 DAA.pdf
 
2.5 dfs & bfs
2.5 dfs & bfs2.5 dfs & bfs
2.5 dfs & bfs
 
Graph Traversals
Graph TraversalsGraph Traversals
Graph Traversals
 
Analysis of Pathfinding Algorithms
Analysis of Pathfinding AlgorithmsAnalysis of Pathfinding Algorithms
Analysis of Pathfinding Algorithms
 
Graph
GraphGraph
Graph
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
Sec B Graph traversal.pptx
Sec B Graph traversal.pptxSec B Graph traversal.pptx
Sec B Graph traversal.pptx
 
Analysis and design of algorithms part 3
Analysis and design of algorithms part 3Analysis and design of algorithms part 3
Analysis and design of algorithms part 3
 

More from Rajandeep Gill (7)

Chronic Kidney Disease Prediction
Chronic Kidney Disease PredictionChronic Kidney Disease Prediction
Chronic Kidney Disease Prediction
 
4. avl
4. avl4. avl
4. avl
 
Asymptotic Notation and Complexity
Asymptotic Notation and ComplexityAsymptotic Notation and Complexity
Asymptotic Notation and Complexity
 
Operating system quiz
Operating system quizOperating system quiz
Operating system quiz
 
Deadlock
DeadlockDeadlock
Deadlock
 
Software Engineering Methodology
Software Engineering MethodologySoftware Engineering Methodology
Software Engineering Methodology
 
Enterprise and Enterprise Application
Enterprise and Enterprise ApplicationEnterprise and Enterprise Application
Enterprise and Enterprise Application
 

Recently uploaded

Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Recently uploaded (20)

The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 

Graph traversal-BFS & DFS

  • 1. Graph Traversal Depth-First Search • Using Stack Breadth-First Search • Using Queue
  • 2. Overview • Goal – To systematically visit the nodes of a graph • A tree is a directed, acyclic, graph (DAG) • If the graph is a tree, – DFS is exhibited by preorder, postorder, and (for binary trees) inorder traversals – BFS is exhibited by level-order traversal
  • 3. Depth-First Search // recursive, preorder, depth-first search void dfs (Node v) { if (v == null) return; if (v not yet visited) visit&mark(v); // visit node before adjacent nodes for (each w adjacent to v) if (w has not yet been visited) dfs(w); } // dfs
  • 4. Example 0 7 1 5 4 3 2 6 Policy: Visit adjacent nodes in increasing index order
  • 5. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 2 7 6 4
  • 6. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 Push 5
  • 7. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 Pop/Visit/Mark 5
  • 8. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 2 Push 2, Push 1
  • 9. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 2 Pop/Visit/Mark 1
  • 10. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 4 2 Push 4, Push 0
  • 11. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 4 2 Pop/Visit/Mark 0
  • 12. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 7 4 2 Push 7, Push 3
  • 13. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 7 4 2 Pop/Visit/Mark 3
  • 14. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 7 4 2 2 is already in stack
  • 15. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 7 7 4 2 Pop/Mark/Visit 7
  • 16. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 7 6 4 2 Push 6
  • 17. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 7 6 4 2 Pop/Mark/Visit 6
  • 18. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 7 6 4 2 Pop/Mark/Visit 4
  • 19. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 7 6 4 2 Pop/Mark/Visit 2
  • 20. DFS: Start with Node 5 0 7 1 5 4 3 2 6 5 1 0 3 7 6 4 2 Done
  • 21. Breadth-first Search • Ripples in a pond • Visit designated node • Then visited unvisited nodes a distance i away, where i = 1, 2, 3, etc. • For nodes the same distance away, visit nodes in systematic manner (eg. increasing index order)
  • 22. Breadth-First Search // non-recursive, preorder, breadth-first search void bfs (Node v) { if (v == null) return; enqueue(v); while (queue is not empty) { dequeue(v); if (v has not yet been visited) mark&visit(v); for (each w adjacent to v) if (w has not yet been visited && has not been queued) enqueue(w); } // while } // bfs
  • 23. BFS: Start with Node 5 7 1 5 4 3 2 6 0
  • 24. BFS: Start with Node 5 7 1 5 4 3 2 6 0 5
  • 26. BFS: Visit 1 and add its adjacent nodes 7 1 5 4 3 2 6 5 1 0 5 1 2 0 4
  • 27. BFS: Visit 2 and add its adjacent nodes 7 1 5 4 3 2 6 5 1 2 0 5 1 2 0 4
  • 28. BFS: Visit 0 and add its adjacent nodes 7 1 5 4 3 2 6 5 1 2 0 0 5 1 2 0 4 3 7
  • 29. BFS: Visit 4 and add its adjacent nodes 7 1 5 4 3 2 6 5 1 2 0 4 0 5 1 2 0 4 3 7
  • 30. BFS: Visit 3 and add its adjacent nodes 7 1 5 4 3 2 6 5 1 2 0 4 3 0 5 1 2 0 4 3 7
  • 31. BFS: Visit 7 and add its adjacent nodes 7 1 5 4 3 2 6 5 1 2 0 4 3 7 0 5 1 2 0 4 3 7 6
  • 32. BFS: Visit 6 and add its adjacent nodes 7 1 5 4 3 2 6 5 1 2 0 4 3 7 6 0 5 1 2 0 4 3 7 6
  • 34. Applications of BFS • Computing Distances: Given a source vertex x, compute the distance of all vertices from x. • Checking for cycles in a graph: Given an undirected graph G, report whether there exists a cycle in the graph or not. (Note: won’t work for directed graphs) • Checking for bipartite graph: Given a graph, check whether it is bipartite or not? A graph is said to be bipartite if there is a partition of the vertex set V into two sets V1 and V2 such that if two vertices are adjacent, either both are in V1 or both are in V2. • Reachability: Given a graph G and vertices x and y, determine if there exists a path from x to y.
  • 35. Applications of DFS • Computing Strongly Connected Components: A directed graph is strongly connected if there exists a path from every vertex to every other vertex. Trivial Algo: Perform DFS n times. Efficient Algo: Single DFS. • Checking for Biconnected Graph: A graph is biconnected if removal of any vertex does not affect connectivity of the other vertices. Used to test if network is robust to failure of certain nodes. A single DFS traversal algorithm. • Topological Ordering: Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge (x, y), vertex x comes before y in the ordering