Daa Lab 8 - Dfs and Bfs
Daa Lab 8 - Dfs and Bfs
2
2 3
3 <Empty>
Algorithm DFS_MAIN( G(V, E) )
Mark each vertex in v with 0
for each vertex v in V
if (v is marked with 0)
dfs_recurse(v)
Procedure dfs_recurse(v)
Mark v with 1
for each vertex w in V adjacent to v
if (w is marked with 0)
dfs_recurse(w)
(a) Graph
(b) Stack of the DFS Traversal
(c) DFS Forest
i. Tree edges
ii. Back edges
(a) Graph
(b) Stack of the DFS Traversal
(c) DFS Forest
i. Tree edges
ii. Back edges
Breadth First Search (BFS)
(a) Graph
(b) Queue of the BFS Traversal
(c) BFS Forest
i. Tree edges
ii. Cross edges
Algorithm BFS_main( G(V, E) )
Mark each vertex in v with 0
for each vertex v in V
if(v is marked with 0)
bfs_node(v)
Procedure bfs_node(v)
Mark v with 1 and insert v into the Queue
while the Queue is not empty
v ← remove a vertex from the Queue
for each vertex w in V adjacent to v
if(w is marked with 0)
Mark w with 1
Add w to the Queue
Algorithm BFS(G)
Mark each vertex in v with 0
for each vertex v in V
if(v is marked with 0)
Mark v with 1
Insert v into the Queue
while the Queue is not empty
v ← remove a vertex from the Queue
for each vertex w in V adjacent to v
if(w is marked with 0)
Mark w with 1
Add w to the Queue
Problem for the lab:
Write a program to find the number of
components an undirected graph has. The graph
could be represented as an adjacency matrix.
(a) Using DFS traversal
(b) Using BFS traversal
Sample Output 1:
2
Sample Input 2:
2
0 0
0 0
Sample Output 2:
2
Problem for the lab: Test-cases:
Sample Input 3:
2
0 1
1 0
Sample Output 3:
1
Sample Input 4:
2
1 1
1 1
Sample Output 4:
1
Problem for the lab: Test-cases:
Sample Input 5:
3
0 0 0
0 0 0
0 0 0
Sample Output 5:
3
Sample Input 6:
3
1 1 1
1 0 0
1 0 0
Sample Output 6:
1
Problem for the lab: Test-cases:
Sample Input 7:
1
1
Sample Output 7:
1
Sample Input 8:
9
0 1 1 0 0 0 0 0 0
1 0 0 0 1 0 0 0 0
1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 1
0 0 0 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 1 0 0
Sample Output 8:
4
Practice problem for the lab:
Simulate a maze search using DFS technique.
Represent a 2-dimensional maze by grid of
nodes, where a node in the grid can
potentially connect to four other nodes in
the grid. Two nodes have an edge between them
if they are adjacent in the grid and there is
no obstacle in between. Print the index of
the nodes (i, j) visited during the maze
search. The search ends when all reachable
nodes from (0, 0) are visited.
Practice problem for the lab:
...
Input: ‘r’ rows and ‘c’ columns in the grid.
It is followed by r*c binary strings of 4
bits (like 1001) indicating the connection to
its right, bottom, left and top adjacent
nodes, respectively.