0% found this document useful (0 votes)
17 views95 pages

BFS and DFS 29

The document provides an overview of graph data structures, including definitions of key terminologies such as vertices, edges, and types of graphs. It explains two main graph traversal algorithms: Breadth-First Search (BFS) and Depth-First Search (DFS), detailing their processes and implementations. Additionally, it discusses graph representations through adjacency matrices and lists, along with exercises for practical understanding.

Uploaded by

Piyush Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views95 pages

BFS and DFS 29

The document provides an overview of graph data structures, including definitions of key terminologies such as vertices, edges, and types of graphs. It explains two main graph traversal algorithms: Breadth-First Search (BFS) and Depth-First Search (DFS), detailing their processes and implementations. Additionally, it discusses graph representations through adjacency matrices and lists, along with exercises for practical understanding.

Uploaded by

Piyush Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 95

Graph Traversals

BFS and DFS


Graph Data Structure
• Graph is a non linear data structure, it contains a set of points known
as nodes (or vertices) and set of links known as edges (or Arcs) which
connects the vertices.

• Generally, a graph G is represented as G = ( V , E ), where V is set of


vertices and E is set of edges.
Terminologies
Vertex
•A individual data element of a graph is called as
Vertex. Vertex is also known as node. In above
example graph, A, B, C, D & E are known as vertices.

Edge
•An edge is a connecting link between two
vertices. Edge is also known as Arc. An edge is
represented as (startingVertex, endingVertex).
Terminologies…
Undirected Graph
•A graph with only undirected edges is said to be
undirected graph.
Directed Graph
•A graph with only directed edges is said to be directed
graph.
Adjacent
•If there is an edge between vertices A and B then both A
and B are said to be adjacent. In other words, Two vertices
A and B are said to be adjacent if there is an edge whose
end vertices are A and B.
Terminologies…
Degree
•Total number of edges connected to a vertex is
said to be degree of that vertex.
Indegree
•Total number of incoming edges connected to a
vertex is said to be indegree of that vertex.
Outdegree
•Total number of outgoing edges connected to a
vertex is said to be outdegree of that vertex.
Terminologies…
Self-loop
•An edge (undirected or directed) is a self-loop if its two
endpoints coincide.
Simple Graph
•A graph is said to be simple if there are no parallel and
self-loop edges.
Path
•A path is a sequence of alternating vertices and edges that
starts at a vertex and ends at a vertex such that each edge is
incident to its predecessor and successor vertex.
Graph Representations
• Graph data structure is represented using
following representations...
– Adjacency Matrix
– Adjacency List
Adjacency Matrix
• graph can be represented using a matrix of
size total number of vertices by total
number of vertices.
• This matrix is filled with either 1 or 0. Here,
1 represents there is an edge from row
vertex to column vertex and 0 represents
there is no edge from row vertex to column
vertex.
Adjacency List
• In this representation, every vertex of graph
contains list of its adjacent vertices.
Exercise
• Represent the graph using:
• 1. Adjacency Matrix A->B->C
B->D
• 2. Adjacency List
C
•A
D->C
•A
•B •C
•B •C

•D
•D
Exercise – Adjacency Matrix &
List
What is a Graph?

Graphs are one of the most interesting data structures in


computer science. Graphs and the trees are somewhat
similar by their structure. In fact, tree is derived from the
graph data structure. However there are two important
differences between trees and graphs.
•Unlike trees, in graphs, a node can have many parents.
•Graph may form cycles but Trees don’t
•The link between the nodes may have values or weights.
•Graphs are good in modeling real world problems like
representing cities which are connected by roads and finding the
paths between cities, modeling air traffic controller system, etc.
These kinds of problems are hard to represent using simple tree
structures. The following example shows a very simple graph:
Graph Traversal
The breadth first search (BFS) and
the depth first search (DFS) are the
two algorithms used for traversing
and searching a node in a graph.
They can also be used to find out
whether a node is reachable from a
given node or not.
BFS stands for Breadth First Search is a vertex based
technique for finding a shortest path in graph. It uses
a Queue data structure which follows first in first out. In
BFS, one vertex is selected at a time when it is visited and
marked then its adjacent are visited and stored in the queue.
It is slower than DFS.
Breadth-First Search

• Visiting a node
• Exploring a node

• It performs like level order


Overview
• Breadth-first search starts
F C with given node
A
B D
H
0
G E

Task: Conduct a breadth-first search of


the graph starting with node D
Overview
• Breadth-first search starts
F C with given node
A
• Then visits nodes adjacent
B D in some specified order
H (e.g., alphabetical)
0
G E • Like ripples in a pond
1

Nodes visited: D
Overview
• Breadth-first search starts
F C with given node
A
• Then visits nodes adjacent
B D in some specified order
H (e.g., alphabetical)
0
G E • Like ripples in a pond
1

Nodes visited: D, C
Overview
• Breadth-first search starts
F C with given node
A
• Then visits nodes adjacent
B D in some specified order
H (e.g., alphabetical)
0
G E • Like ripples in a pond
1

Nodes visited: D, C, E
Overview
• Breadth-first search starts
F C with given node
A
• Then visits nodes adjacent
B D in some specified order
H (e.g., alphabetical)
0
G E • Like ripples in a pond
1

Nodes visited: D, C, E, F
Overview
• When all nodes in ripple
F C are visited, visit nodes in
A next ripples
B D
H
0
G E
2 1

Nodes visited: D, C, E, F, G
Overview
• When all nodes in ripple
F C are visited, visit nodes in
A next ripples
B D
H
0
3 G E
2 1

Nodes visited: D, C, E, F, G, H
Overview
4 • When all nodes in ripple
F C are visited, visit nodes in
A next ripples
B D
H
0
3
G E
2 1

Nodes visited: D, C, E, F, G, H, A
Overview
4 • When all nodes in ripple
F C are visited, visit nodes in
A next ripples
B D
H
0
3
G E
2 1

Nodes visited: D, C, E, F, G, H, A, B
Walk-Through
Enqueued Array
F C A
A B Q
B C
D
H D
E
G E F
G
H

How is this accomplished? Simply replace the stack


with a queue! Rules: (1) Maintain an enqueued
array. (2) Visit node when dequeued.
Walk-Through
Enqueued Array
F C A
A B QD
B C
D
H D √
E
G E F
G
Nodes visited: H

Enqueue D. Notice, D not yet visited.


Walk-Through
Enqueued Array
F C A
A B QCEF
B C √
D
H D √
E √
G E F √
G
Nodes visited: D H

Dequeue D. Visit D. Enqueue unenqueued nodes


adjacent to D.
Walk-Through
Enqueued Array
F C A
A B QEF
B C √
D
H D √
E √
G E F √
G
Nodes visited: D, C H

Dequeue C. Visit C. Enqueue unenqueued nodes


adjacent to C.
Walk-Through
Enqueued Array
F C A
A B QFG
B C √
D
H D √
E √
G E F √
G
Nodes visited: D, C, E H

Dequeue E. Visit E. Enqueue unenqueued nodes


adjacent to E.
Walk-Through
Enqueued Array
F C A
A B QG
B C √
D
H D √
E √
G E F √
G √
Nodes visited: D, C, E, F H

Dequeue F. Visit F. Enqueue unenqueued nodes


adjacent to F.
Walk-Through
Enqueued Array
F C A
A B QH
B C √
D
H D √
E √
G E F √
G √
Nodes visited: D, C, E, F, G H √

Dequeue G. Visit G. Enqueue unenqueued nodes


adjacent to G.
Walk-Through
Enqueued Array
F C A √
A B √ QAB
B C √
D
H D √
E √
G E F √
G √
Nodes visited: D, C, E, F, G, H H √

Dequeue H. Visit H. Enqueue unenqueued nodes


adjacent to H.
Walk-Through
Enqueued Array
F C A √
A B √ QB
B C √
D
H D √
E √
G E F √
G √
Nodes visited: D, C, E, F, G, H, H √
A
Dequeue A. Visit A. Enqueue unenqueued nodes
adjacent to A.
Walk-Through
Enqueued Array
F C A √
A B √ Q empty
B C √
D
H D √
E √
G E F √
G √
Nodes visited: D, C, E, F, G, H, H √
A, B
Dequeue B. Visit B. Enqueue unenqueued nodes
adjacent to B.
Walk-Through
Enqueued Array
F C A √
A B √ Q empty
B C √
D
H D √
E √
G E F √
G √
Nodes visited: D, C, E, F, G, H, H √
A, B
Q empty. Algorithm done.
BFS (Breadth First Search)
BFS traversal of a graph, produces a spanning tree as final
result. Spanning Tree is a graph without any loops. We use Queue
data structure with maximum size of total number of vertices in
the graph to implement BFS traversal of a graph.
We use the following steps to implement BFS traversal...
•Step 1: Define a Queue of size total number of vertices in the
graph.
•Step 2: Select any vertex as starting point for traversal. Visit that
vertex and insert it into the Queue.
•Step 3: Visit all the adjacent vertices of the vertex which is at
front of the Queue which is not visited and insert them into the
Queue.
•Step 4: When there is no new vertex to be visit from the vertex at
front of the Queue then delete that vertex from the Queue.
•Step 5: Repeat step 3 and 4 until queue becomes empty.
•Step 6: When queue becomes Empty, then produce final spanning
tree by removing unused edges from the graph
Exercise: 1
Exercise: 2
HW
ALGORITHM BFS(G)
//Implements a breadth-first search traversal of a given graph
//Input: Graph G=(V,E)
//Output: Graph G with its vertices marked with consecutive
integers in the order they are visited by the BFS traversal
mark each vertex in V with 0 as a mark of being “unvisited”
count ←0
for each vertex v in V do
if v is marked with 0
BFS(v)
BFS(v)
//visits all the unvisited vertices connected to vertex v by a path and
numbers them in the order they are visited via global variable
count
count ←count +1; mark v with count and initialize a
queue with v
while the queue is not empty do
for each vertex w in V adjacent to the front
vertex do
if w is marked with 0
count ←count +1; mark w with count
add w to the queue
remove the front vertex from the queue
DFS ( Depth First Search)
Depth First Search

• Visiting a node

• Exploring a node
Depth First Search
DFS stands for Depth First Search is a edge based technique.
It uses the Stack Data Structure, performs two stages, first
visited vertices are pushed into stack and second if there is no
vertices then visited vertices are popped.

A,B,D,C,E,F
DFS
Walk-Through
Visited Array
F C A
A B
B C
D
H D
E
G E F
G
H

Task: Conduct a depth-first search of the


graph starting with node D
Walk-Through
Visited Array
F C A
A B
B C
D
H D √
E
G E F
G
H D
The order nodes are visited:
Visit D
D
Walk-Through
Visited Array
F C A
A B
B C
D
H D √
E
G E F
G
H D
The order nodes are visited:
Consider nodes adjacent to D,
D decide to visit C first (Rule:
visit adjacent nodes in
alphabetical order)
Walk-Through
Visited Array
F C A
A B
B C √
D
H D √
E
G E F
G C
H D
The order nodes are visited:
Visit C
D, C
Walk-Through
Visited Array
F C A
A B
B C √
D
H D √
E
G E F
G C
H D
The order nodes are visited:
No nodes adjacent to C; cannot
D, C continue  backtrack, i.e.,
pop stack and restore
previous state
Walk-Through
Visited Array
F C A
A B
B C √
D
H D √
E
G E F
G
H D
The order nodes are visited:
Back to D – C has been visited,
D, C decide to visit E next
Walk-Through
Visited Array
F C A
A B
B C √
D
H D √
E √
G E F
G E
H D
The order nodes are visited:
Back to D – C has been visited,
D, C, E decide to visit E next
Walk-Through
Visited Array
F C A
A B
B C √
D
H D √
E √
G E F
G E
H D
The order nodes are visited:
Only G is adjacent to E
D, C, E
Walk-Through
Visited Array
F C A
A B
B C √
D
H D √
E √
G E F
G

G √ E
H D
The order nodes are visited:
Visit G
D, C, E, G
Walk-Through
Visited Array
F C A
A B
B C √
D
H D √
E √
G E F
G

G √ E
H D
The order nodes are visited:
Nodes D and H are adjacent to
D, C, E, G G. D has already been
visited. Decide to visit H.
Walk-Through
Visited Array
F C A
A B
B C √
D
H D √
H
E √
G E F
G

G √ E
H √ D
The order nodes are visited:
Visit H
D, C, E, G, H
Walk-Through
Visited Array
F C A
A B
B C √
D
H D √
H
E √
G E F
G

G √ E
H √ D
The order nodes are visited:
Nodes A and B are adjacent to H.
D, C, E, G, H Decide to visit A next.
Walk-Through
Visited Array
F C A √
A B
B C √
D A
H D √
H
E √
G E F
G

G √ E
H √ D
The order nodes are visited:
Visit A
D, C, E, G, H, A
Walk-Through
Visited Array
F C A √
A B
B C √
D A
H D √
H
E √
G E F
G

G √ E
H √ D
The order nodes are visited:
Only Node B is adjacent to A.
D, C, E, G, H, A Decide to visit B next.
Walk-Through
Visited Array
F C A √
A B √ B
B C √
D A
H D √
H
E √
G E F
G

G √ E
H √ D
The order nodes are visited:
Visit B
D, C, E, G, H, A, B
Walk-Through
Visited Array
F C A √
A B √
B C √
D A
H D √
H
E √
G E F
G

G √ E
H √ D
The order nodes are visited:
No unvisited nodes adjacent to
D, C, E, G, H, A, B B. Backtrack (pop the stack).
Walk-Through
Visited Array
F C A √
A B √
B C √
D
H D √
H
E √
G E F
G

G √ E
H √ D
The order nodes are visited:
No unvisited nodes adjacent to
D, C, E, G, H, A, B A. Backtrack (pop the stack).
Walk-Through
Visited Array
F C A √
A B √
B C √
D
H D √
E √
G E F
G

G √ E
H √ D
The order nodes are visited:
No unvisited nodes adjacent to
D, C, E, G, H, A, B H. Backtrack (pop the
stack).
Walk-Through
Visited Array
F C A √
A B √
B C √
D
H D √
E √
G E F
G √ E
H √ D
The order nodes are visited:
No unvisited nodes adjacent to
D, C, E, G, H, A, B G. Backtrack (pop the
stack).
Walk-Through
Visited Array
F C A √
A B √
B C √
D
H D √
E √
G E F
G √
H √ D
The order nodes are visited:
No unvisited nodes adjacent to
D, C, E, G, H, A, B E. Backtrack (pop the stack).
Walk-Through
Visited Array
F C A √
A B √
B C √
D
H D √
E √
G E F
G √
H √ D
The order nodes are visited:
F is unvisited and is adjacent to
D, C, E, G, H, A, B D. Decide to visit F next.
Walk-Through
Visited Array
F C A √
A B √
B C √
D
H D √
E √
G E F √
G √ F
H √ D
The order nodes are visited:
Visit F
D, C, E, G, H, A, B, F
Walk-Through
Visited Array
F C A √
A B √
B C √
D
H D √
E √
G E F √
G √
H √ D
The order nodes are visited:
No unvisited nodes adjacent to
D, C, E, G, H, A, B, F F. Backtrack.
Walk-Through
Visited Array
F C A √
A B √
B C √
D
H D √
E √
G E F √
G √
H √
The order nodes are visited:
No unvisited nodes adjacent to
D, C, E, G, H, A, B, F D. Backtrack.
Walk-Through
Visited Array
F C A √
A B √
B C √
D
H D √
E √
G E F √
G √
H √
The order nodes are visited:
Stack is empty. Depth-first
D, C, E, G, H, A, B, F traversal is done.
DFS (Depth First Search)
• DFS traversal of a graph, produces a spanning tree as final result. Spanning Tree
is a graph without any loops. We use Stack data structure with maximum size of
total number of vertices in the graph to implement DFS traversal of a graph.
Step 1: Define a Stack of size total number of vertices in the graph.
Step 2: Select any vertex as starting point for traversal. Visit that vertex & push it
on to the Stack.
Step 3: Visit any one of the adjacent vertex of the verex which is at top of the stack
which is not visited and push it on to the stack.
Step 4: Repeat step 3 until there are no new vertex to be visit from the vertex on
top of the stack.
Step 5: When there is no new vertex to be visit then use back tracking and pop one
vertex from the stack.
Step 6: Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7: When stack becomes Empty, then produce final spanning tree by removing
unused edges from the graph
Back tracking is coming back to the vertex from which we came to current vertex.
ALGORITHM
DFS(G)
//Implements a depth-first search traversal of a given graph
//Input: Graph G=(V,E)
//Output: Graph G with its vertices marked with consecutive
integers
// in the order they are first encountered by the DFS traversal
mark each vertex in V with 0 as a mark of being “unvisited”
count ←0
for each vertex v in V do
if v is marked with 0
dfs(v)
dfs(v)
//visits recursively all the unvisited vertices connected to
vertex v by a path and numbers them in the order they are
encountered via global variable count
count ←count +1; mark v with count
for each vertex w in V adjacent to v do
if w is marked with 0
dfs(w)
Find the BFS and DFS and construct
BFS AND DFS SPANNING TREE
Cross Edge
S.NO BFS DFS
BFS(Breadth First Search) DFS(Depth First Search) uses
uses Queue data structure Stack data structure.
1 for finding the shortest
path.

BFS can be used to find In DFS, we might traverse


single source shortest through more edges to reach a
path in an un weighted destination vertex from a source.
graph, because in BFS, we
2.
reach a vertex with
minimum number of
edges from a source
vertex.
DFS is more suitable when
BFS is more suitable for
there are solutions away from
3. searching vertices which are
source.
closer to the given source.
DFS is more suitable for game
BFS considers all neighbors
or puzzle problems. We make a
first and therefore not
decision, then explore all paths
4. suitable for decision making
through this decision. And if
trees used in games or
this decision leads to win
puzzles.
situation, we stop.
The Time complexity of BFS
The Time complexity of DFS is
is O(V + E), where V and E
5. also O(V + E), where V and E
stands for vertices and
stands for vertices and edges.
edges.

You might also like