SlideShare a Scribd company logo
Graph Traversals
• Depth-First Traversals.
– Algorithms.
– Example.
– Implementation.
• Breadth-First Traversal.
– The Algorithm.
– Example.
– Implementation.
• Review Questions.
Depth-First Traversal Algorithm
• In this method, After visiting a vertex v, which is adjacent to w1, w2,
w3, ...; Next we visit one of v's adjacent vertices, w1 say. Next, we
visit all vertices adjacent to w1 before coming back to w2, etc.
• Must keep track of vertices already visited to avoid cycles.
• The method can be implemented using recursion or iteration.
• The iterative preorder depth-first algorithm is:
1 push the starting vertex onto the stack
2 while(stack is not empty){
3 pop a vertex off the stack, call it v
4 if v is not already visited, visit it
5 push vertices adjacent to v, not visited, onto the stack
6 }
• Note: Adjacent vertices can be pushed in any order; but to obtain a unique
traversal, we will push them in reverse alphabetical order.
Example
• Demonstrates depth-first traversal using an explicit stack.
Order of
Traversal StackA B C F E G D H I
Recursive preorder Depth-First Traversal Implementation
• The following is the code for the recursive preorderDepthFirstTraversal
method of the AbstractGraph class:
public void preorderDepthFirstTraversal(Visitor visitor, Vertex start)
{
boolean visited[] = new boolean[numberOfVertices];
for(int v = 0; v < numberOfVertices; v++)
visited[v] = false;
preorderDepthFirstTraversal(visitor, start, visited);
}
dfsPreorder(v(}
visit v;
for(each neighbour w of v(
if(w has not been visited(
dfsPreorder(w(;
}
Recursive preorder Depth-First Traversal Implementation (cont’d)
private void preorderDepthFirstTraversal(Visitor visitor,
Vertex v, boolean[] visited)
{
if(visitor.isDone())
return;
visitor.visit(v);
visited[getIndex(v)] = true;
Iterator p = v.getSuccessors();
while(p.hasNext()) {
Vertex to = (Vertex) p.next();
if(! visited[getIndex(to)])
preorderDepthFirstTraversal(visitor, to,
visited);
}
}
Recursive preorder Depth-First Traversal Implementation (cont’d)
At each stage, a set of unvisited
adjacent vertices of the current vertex
is generated.
Recursive postorder Depth-First Traversal Implementation
public void postorderDepthFirstTraversal(Visitor visitor,
Vertex start)
{
boolean visited[] = new boolean[numberOfVertices];
for(int v = 0; v < numberOfVertices; v++)
visited[v] = false;
postorderDepthFirstTraversal(visitor, start, visited);
}
dfsPostorder(v(}
mark v;
for(each neighbour w of v(
if(w is not marked(
dfsPostorder(w(;
visit v;
}
•The following is the code for the recursive postorderDepthFirstTraversal method
of the AbstractGraph class:
Recursive postorder Depth-First Traversal Implementation (cont’d)
private void postorderDepthFirstTraversal(
Visitor visitor, Vertex v, boolean[] visited)
{
if(visitor.isDone())
return;
// mark v
visited[getIndex(v)] = true;
Iterator p = v.getSuccessors();
while(p.hasNext()){
Vertex to = (Vertex) p.next();
if(! visited[getIndex(to)])
postorderDepthFirstTraversal(visitor, to,
visited);
}
// visit v
visitor.visit(v);
}
Recursive postorder Depth-First Traversal Implementation (cont’d)
At each stage, a set of unmarked
adjacent vertices of the current vertex
is generated.
Breadth-First Traversal Algorithm
• In this method, After visiting a vertex v, we must visit all its adjacent
vertices w1, w2, w3, ..., before going down next level to visit
vertices adjacent to w1 etc.
• The method can be implemented using a queue.
• A boolean array is used to ensure that a vertex is enqueued only
once.
1 enqueue the starting vertex
2 while(queue is not empty){
3 dequeue a vertex v from the queue;
4 visit v.
5 enqueue vertices adjacent to v that were never enqueued;
6 }
• Note: Adjacent vertices can be enqueued in any order; but to obtain a unique
traversal, we will enqueue them in alphabetical order.
Example
• Demonstrating breadth-first traversal using a queue.
Order of
Traversal Queue rearA B D E C G F H I
Queue front
Breadth-First Traversal Implementation
public void breadthFirstTraversal(Visitor visitor, Vertex start){
boolean enqueued[] = new boolean[numberOfVertices];
for(int i = 0; i < numberOfVertices; i++) enqueued[i] = false;
Queue queue = new QueueAsLinkedList();
enqueued[getIndex(start)] = true;
queue.enqueue(start);
while(!queue.isEmpty() && !visitor.isDone()) {
Vertex v = (Vertex) queue.dequeue();
visitor.visit(v);
Iterator it = v.getSuccessors();
while(it.hasNext()) {
Vertex to = (Vertex) it.next();
int index = getIndex(to);
if(!enqueued[index]) {
enqueued[index] = true;
queue.enqueue(to);
}
}
}
}
Review Questions
1. Considera depth-first traversal of the undirected graph GA shown above,
starting from vertex a.
• List the order in which the nodes are visited in a preorder traversal.
• List the order in which the nodes are visited in a postorder traversal
2. Repeat exercise 1 above for a depth-first traversal starting from vertex d.
3. List the order in which the nodes of the undirected graph GA shown above are
visited by a breadth first traversal that starts from vertex a. Repeat this
exercise for a breadth-first traversal starting from vertex d.
4. Repeat Exercises 1 and 3 for the directed graph GB.

More Related Content

PPSX
Data Structure (Tree)
PPTX
PPTX
B and B+ tree
PPTX
Array operations
PPSX
Data Structure (Queue)
PPTX
Binary expression tree
PPTX
Binary Tree Traversal
PDF
linked lists in data structures
Data Structure (Tree)
B and B+ tree
Array operations
Data Structure (Queue)
Binary expression tree
Binary Tree Traversal
linked lists in data structures

What's hot (20)

PPT
Binary tree
PPTX
Stack and Queue
PPTX
heap Sort Algorithm
PPTX
Binary Search Tree
PPTX
BINARY SEARCH TREE
PPT
Data Structures with C Linked List
PPTX
Balanced Tree (AVL Tree & Red-Black Tree)
PPT
Heap tree
PPTX
Stacks and Queue - Data Structures
PPTX
trees in data structure
PPTX
Graph representation
PPTX
Data Structures - Lecture 8 [Sorting Algorithms]
PPTX
Bfs & dfs application
PPTX
Linked list
PPTX
Linked List
PPTX
Merge sort algorithm power point presentation
PPTX
My lectures circular queue
PPTX
Deque and its applications
PPT
PPTX
Trees in data structure
Binary tree
Stack and Queue
heap Sort Algorithm
Binary Search Tree
BINARY SEARCH TREE
Data Structures with C Linked List
Balanced Tree (AVL Tree & Red-Black Tree)
Heap tree
Stacks and Queue - Data Structures
trees in data structure
Graph representation
Data Structures - Lecture 8 [Sorting Algorithms]
Bfs & dfs application
Linked list
Linked List
Merge sort algorithm power point presentation
My lectures circular queue
Deque and its applications
Trees in data structure
Ad

Viewers also liked (19)

PPT
2.5 graph dfs
PPTX
Graph Traversal Algorithms - Depth First Search Traversal
PPT
2.5 bfs & dfs 02
PPT
1.5 weka an intoduction
PDF
Graph applications chapter
PPTX
Graphs Algorithms
PPT
5.5 back tracking
PPT
2.3 shortest path dijkstra’s
PPT
Graph theory
PPTX
Graph Traversal Algorithm
PPT
5.5 back track
PPT
4.4 external hashing
PPT
2.4 rule based classification
PPTX
PPT
Breadth first search
PPTX
Graph Traversal Algorithms - Breadth First Search
PPT
Graphs bfs dfs
PPT
Bfs and dfs in data structure
PDF
introduction to graph theory
2.5 graph dfs
Graph Traversal Algorithms - Depth First Search Traversal
2.5 bfs & dfs 02
1.5 weka an intoduction
Graph applications chapter
Graphs Algorithms
5.5 back tracking
2.3 shortest path dijkstra’s
Graph theory
Graph Traversal Algorithm
5.5 back track
4.4 external hashing
2.4 rule based classification
Breadth first search
Graph Traversal Algorithms - Breadth First Search
Graphs bfs dfs
Bfs and dfs in data structure
introduction to graph theory
Ad

Similar to 2.5 dfs & bfs (8)

PPT
Graph traversal-BFS & DFS
PPT
cs201-tree-graph as a data structure.ppt
PPTX
PDF
Analysis of Pathfinding Algorithms
PPT
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
PPTX
kjugyfdtryuytrdtfyugtfdxghjgfdial algorithm.pptx
PPTX
Internet Download Manager Crack Patch Latest IDM Free
PPTX
Breath first Search and Depth first search
Graph traversal-BFS & DFS
cs201-tree-graph as a data structure.ppt
Analysis of Pathfinding Algorithms
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
kjugyfdtryuytrdtfyugtfdxghjgfdial algorithm.pptx
Internet Download Manager Crack Patch Latest IDM Free
Breath first Search and Depth first search

More from Krish_ver2 (20)

PPT
5.5 back tracking 02
PPT
5.4 randomized datastructures
PPT
5.4 randomized datastructures
PPT
5.4 randamized algorithm
PPT
5.3 dynamic programming 03
PPT
5.3 dynamic programming
PPT
5.3 dyn algo-i
PPT
5.2 divede and conquer 03
PPT
5.2 divide and conquer
PPT
5.2 divede and conquer 03
PPT
5.1 greedyyy 02
PPT
5.1 greedy
PPT
5.1 greedy 03
PPT
4.4 hashing02
PPT
4.4 hashing
PPT
4.4 hashing ext
PPT
4.2 bst
PPT
4.2 bst 03
PPT
4.2 bst 02
PPT
4.1 sequentioal search
5.5 back tracking 02
5.4 randomized datastructures
5.4 randomized datastructures
5.4 randamized algorithm
5.3 dynamic programming 03
5.3 dynamic programming
5.3 dyn algo-i
5.2 divede and conquer 03
5.2 divide and conquer
5.2 divede and conquer 03
5.1 greedyyy 02
5.1 greedy
5.1 greedy 03
4.4 hashing02
4.4 hashing
4.4 hashing ext
4.2 bst
4.2 bst 03
4.2 bst 02
4.1 sequentioal search

Recently uploaded (20)

PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Cell Types and Its function , kingdom of life
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
Trump Administration's workforce development strategy
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Classroom Observation Tools for Teachers
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
RMMM.pdf make it easy to upload and study
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Pharma ospi slides which help in ospi learning
PDF
Complications of Minimal Access Surgery at WLH
PDF
Microbial disease of the cardiovascular and lymphatic systems
Supply Chain Operations Speaking Notes -ICLT Program
Anesthesia in Laparoscopic Surgery in India
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
human mycosis Human fungal infections are called human mycosis..pptx
Cell Types and Its function , kingdom of life
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Trump Administration's workforce development strategy
O7-L3 Supply Chain Operations - ICLT Program
STATICS OF THE RIGID BODIES Hibbelers.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Classroom Observation Tools for Teachers
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
RMMM.pdf make it easy to upload and study
01-Introduction-to-Information-Management.pdf
Final Presentation General Medicine 03-08-2024.pptx
Pharma ospi slides which help in ospi learning
Complications of Minimal Access Surgery at WLH
Microbial disease of the cardiovascular and lymphatic systems

2.5 dfs & bfs

  • 1. Graph Traversals • Depth-First Traversals. – Algorithms. – Example. – Implementation. • Breadth-First Traversal. – The Algorithm. – Example. – Implementation. • Review Questions.
  • 2. Depth-First Traversal Algorithm • In this method, After visiting a vertex v, which is adjacent to w1, w2, w3, ...; Next we visit one of v's adjacent vertices, w1 say. Next, we visit all vertices adjacent to w1 before coming back to w2, etc. • Must keep track of vertices already visited to avoid cycles. • The method can be implemented using recursion or iteration. • The iterative preorder depth-first algorithm is: 1 push the starting vertex onto the stack 2 while(stack is not empty){ 3 pop a vertex off the stack, call it v 4 if v is not already visited, visit it 5 push vertices adjacent to v, not visited, onto the stack 6 } • Note: Adjacent vertices can be pushed in any order; but to obtain a unique traversal, we will push them in reverse alphabetical order.
  • 3. Example • Demonstrates depth-first traversal using an explicit stack. Order of Traversal StackA B C F E G D H I
  • 4. Recursive preorder Depth-First Traversal Implementation • The following is the code for the recursive preorderDepthFirstTraversal method of the AbstractGraph class: public void preorderDepthFirstTraversal(Visitor visitor, Vertex start) { boolean visited[] = new boolean[numberOfVertices]; for(int v = 0; v < numberOfVertices; v++) visited[v] = false; preorderDepthFirstTraversal(visitor, start, visited); } dfsPreorder(v(} visit v; for(each neighbour w of v( if(w has not been visited( dfsPreorder(w(; }
  • 5. Recursive preorder Depth-First Traversal Implementation (cont’d) private void preorderDepthFirstTraversal(Visitor visitor, Vertex v, boolean[] visited) { if(visitor.isDone()) return; visitor.visit(v); visited[getIndex(v)] = true; Iterator p = v.getSuccessors(); while(p.hasNext()) { Vertex to = (Vertex) p.next(); if(! visited[getIndex(to)]) preorderDepthFirstTraversal(visitor, to, visited); } }
  • 6. Recursive preorder Depth-First Traversal Implementation (cont’d) At each stage, a set of unvisited adjacent vertices of the current vertex is generated.
  • 7. Recursive postorder Depth-First Traversal Implementation public void postorderDepthFirstTraversal(Visitor visitor, Vertex start) { boolean visited[] = new boolean[numberOfVertices]; for(int v = 0; v < numberOfVertices; v++) visited[v] = false; postorderDepthFirstTraversal(visitor, start, visited); } dfsPostorder(v(} mark v; for(each neighbour w of v( if(w is not marked( dfsPostorder(w(; visit v; } •The following is the code for the recursive postorderDepthFirstTraversal method of the AbstractGraph class:
  • 8. Recursive postorder Depth-First Traversal Implementation (cont’d) private void postorderDepthFirstTraversal( Visitor visitor, Vertex v, boolean[] visited) { if(visitor.isDone()) return; // mark v visited[getIndex(v)] = true; Iterator p = v.getSuccessors(); while(p.hasNext()){ Vertex to = (Vertex) p.next(); if(! visited[getIndex(to)]) postorderDepthFirstTraversal(visitor, to, visited); } // visit v visitor.visit(v); }
  • 9. Recursive postorder Depth-First Traversal Implementation (cont’d) At each stage, a set of unmarked adjacent vertices of the current vertex is generated.
  • 10. Breadth-First Traversal Algorithm • In this method, After visiting a vertex v, we must visit all its adjacent vertices w1, w2, w3, ..., before going down next level to visit vertices adjacent to w1 etc. • The method can be implemented using a queue. • A boolean array is used to ensure that a vertex is enqueued only once. 1 enqueue the starting vertex 2 while(queue is not empty){ 3 dequeue a vertex v from the queue; 4 visit v. 5 enqueue vertices adjacent to v that were never enqueued; 6 } • Note: Adjacent vertices can be enqueued in any order; but to obtain a unique traversal, we will enqueue them in alphabetical order.
  • 11. Example • Demonstrating breadth-first traversal using a queue. Order of Traversal Queue rearA B D E C G F H I Queue front
  • 12. Breadth-First Traversal Implementation public void breadthFirstTraversal(Visitor visitor, Vertex start){ boolean enqueued[] = new boolean[numberOfVertices]; for(int i = 0; i < numberOfVertices; i++) enqueued[i] = false; Queue queue = new QueueAsLinkedList(); enqueued[getIndex(start)] = true; queue.enqueue(start); while(!queue.isEmpty() && !visitor.isDone()) { Vertex v = (Vertex) queue.dequeue(); visitor.visit(v); Iterator it = v.getSuccessors(); while(it.hasNext()) { Vertex to = (Vertex) it.next(); int index = getIndex(to); if(!enqueued[index]) { enqueued[index] = true; queue.enqueue(to); } } } }
  • 13. Review Questions 1. Considera depth-first traversal of the undirected graph GA shown above, starting from vertex a. • List the order in which the nodes are visited in a preorder traversal. • List the order in which the nodes are visited in a postorder traversal 2. Repeat exercise 1 above for a depth-first traversal starting from vertex d. 3. List the order in which the nodes of the undirected graph GA shown above are visited by a breadth first traversal that starts from vertex a. Repeat this exercise for a breadth-first traversal starting from vertex d. 4. Repeat Exercises 1 and 3 for the directed graph GB.