0% found this document useful (0 votes)
31 views32 pages

17-BFS, DFS-05-02-2025

The document provides an overview of Breadth-First Search (BFS) and Depth-First Search (DFS) algorithms for traversing graphs or tree data structures. It details the algorithms' processes, pseudocode, implementations in Java, and their time and space complexities. Additionally, it outlines various applications for both BFS and DFS in different scenarios such as web crawling, cycle detection, and finding paths in graphs.

Uploaded by

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

17-BFS, DFS-05-02-2025

The document provides an overview of Breadth-First Search (BFS) and Depth-First Search (DFS) algorithms for traversing graphs or tree data structures. It details the algorithms' processes, pseudocode, implementations in Java, and their time and space complexities. Additionally, it outlines various applications for both BFS and DFS in different scenarios such as web crawling, cycle detection, and finding paths in graphs.

Uploaded by

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

BFS,DFS

BREADTH-FIRST SEARCH
INTRODUCTION

Breadth First Traversal or Breadth First Search is a


recursive algorithm for searching all the vertices of a graph
or tree data structure.

A standard BFS implementation puts each vertex of the graph


into one of two categories:

1. Visited
2. Not Visited

The purpose of the algorithm is to mark each vertex as


visited while avoiding cycles.
ALGORITHM
BREADTH-FIRST SEARCH

The algorithm works as follows:

• Start by putting any one of the graph's vertices at the back


of a queue.

• Take the front item of the queue and add it to the visited
list.

• Create a list of that vertex's adjacent nodes. Add the ones


which are not in the visited list to the back of the queue.

• Keep repeating steps 2 and 3 until the queue is empty.

• The graph might have two different disconnected parts so to


make sure that we cover every vertex, we can also run the
BFS algorithm on every node
BREADTH-FIRST SEARCH
Example
Step1: Initially queue and visited arrays are empty.
BREADTH-FIRST SEARCH

Step2: Push node 0 into queue and mark it visited.


BREADTH-FIRST SEARCH
Step3: Remove node 0 from the front of queue and visit the
unvisited neighbours and push them into queue.
BREADTH-FIRST SEARCH
Step 4: Remove node 1 from the front of queue and visit
the unvisited neighbours and push them into queu.
BREADTH-FIRST SEARCH
Step 5: Remove node 2 from the front of queue and visit
the unvisited neighbours and push them into queue.
BREADTH-FIRST SEARCH
Step 6: Remove node 3 from the front of queue and visit the
unvisited neighbours and push them into queue. As we can see that
every neighbours of node 3 is visited, so move to the next node
that are in the front of the queue.
BREADTH-FIRST SEARCH
Step 7: Remove node 4 from the front of queue and visit the
unvisited neighbours and push them into queue.
As we can see that every neighbours of node 4 are visited, so move
to the next node that is in the front of the queue.
Now, Queue becomes empty, So, terminate these process of
iteration.
BREADTH-FIRST SEARCH

Pseudocode

create a queue Q
mark v as visited and put v into Q
while Q is non-empty
remove the head u of Q
mark and enqueue all (unvisited) neighbours of u
BREADTH-FIRST SEARCH

Program: BFS Implementation

bfs.java

Time Complexity: O(V + E)


Space Complexity: O(V)

where V is the number of nodes and E is the number of edges


BREADTH-FIRST SEARCH
import java.util.*; LinkedList<Integer> queue = new
public class Graph { LinkedList();
private int V; visited[s] = true;
private LinkedList<Integer> queue.add(s);
adj[]; while (queue.size() != 0) {
// Create a graph s = queue.poll();
Graph(int v) { System.out.print(s + " ");
V = v; Iterator<Integer> i =
adj = new LinkedList[v]; adj[s].listIterator();
for (int i = 0; i < v; ++i) while (i.hasNext()) {
adj[i] = new LinkedList(); int n = i.next();
} if (!visited[n]) {
// Add edges to the graph visited[n] = true;
void addEdge(int v, int w) { queue.add(n);
adj[v].add(w); }
} }
// BFS algorithm }
void BFS(int s) { }
boolean visited[] = new
boolean[V];
BREADTH-FIRST SEARCH
public static void main(String args[]) {
Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println("Following is Breadth First Traversal " +


"(starting from vertex 2)");

g.BFS(2);
}
}
BREADTH-FIRST SEARCH
Applications of BFS

▪ BFS can be used to find the neighboring locations from a given source
location.

▪ In a peer-to-peer network, BFS algorithm can be used as a traversal method


to find all the neighboring nodes.

▪ BFS can be used in web crawlers to create web page indexes where, every web
page is considered as a node in the graph.

▪ BFS is used to determine the shortest path and minimum spanning tree.

▪ BFS is also used in Cheney's technique to duplicate the garbage collection.

▪ It can be used in Ford-Fulkerson method to compute the maximum flow in a


flow network.

▪ It can be used in cycle detection in an undirected graph and also in


navigation
DEPTH -FIRST SEARCH
Introduction

Depth first Search or Depth first traversal is a recursive


algorithm for searching all the vertices of a graph or tree
data structure

A standard DFS implementation puts each vertex of the graph


into one of two categories:

1. Visited
2. Not Visited

The purpose of the algorithm is to mark each vertex as


visited while avoiding cycles.
DEPTH -FIRST SEARCH
Algorithm

• Start by putting any one of the graph's vertices on top of


a stack.

• Take the top item of the stack and add it to the visited
list.

• Create a list of that vertex's adjacent nodes. Add the


ones which aren't in the visited list to the top of the
stack.

• Keep repeating steps 2 and 3 until the stack is empty.


DEPTH -FIRST SEARCH
Step1: Initially stack and visited arrays are empty.
DEPTH -FIRST SEARCH
Step 2: Visit 0 and put its adjacent nodes which are not visited yet
into the stack.
DEPTH -FIRST SEARCH
Step 3: Now, Node 1 at the top of the stack, so visit node 1
and pop it from the stack and put all of its adjacent nodes
which are not visited in the stack.
DEPTH -FIRST SEARCH
Step 4: Now, Node 2 at the top of the stack, so visit node 2
and pop it from the stack and put all of its adjacent nodes
which are not visited (i.e, 3, 4) in the stack.
DEPTH -FIRST SEARCH
Step 5: Now, Node 4 at the top of the stack, so visit node 4
and pop it from the stack and put all of its adjacent nodes
which are not visited in the stack.
DEPTH -FIRST SEARCH
Step 5: Now, Node 4 at the top of the stack, so visit node 4
and pop it from the stack and put all of its adjacent nodes
which are not visited in the stack..
DEPTH -FIRST SEARCH
Step 6: Now, Node 3 at the top of the stack, so visit node 3 and pop
it from the stack and put all of its adjacent nodes which are not
visited in the stack.
Now, Stack becomes empty, which means we have visited all the nodes
and our DFS traversal ends.
DEPTH -FIRST SEARCH

Pseudocode

DFS(G, u)
u.visited = true
for each v ∈
G.Adj[u]
if v.visited ==
false
DFS(G,v)

init() {
For each u ∈ G
u.visited =
false
For each u ∈ G
DFS(G, u)
}
DEPTH -FIRST SEARCH
Program: DFS Implementation

dfs.java

Time Complexity: O(V + E)


Space Complexity: O(V)

where V is the number of nodes and E is the number of edges


DEPTH -FIRST SEARCH
import java.util.*; void addEdge(int src, int dest) {
class Graph { adjLists[src].add(dest);
private LinkedList<Integer> }
adjLists[]; void DFS(int vertex) {
private boolean visited[]; visited[vertex] = true;
// Graph creation System.out.print(vertex + " ");
Graph(int vertices) { Iterator<Integer> ite =
adjLists = new adjLists[vertex].listIterator();
LinkedList[vertices]; while (ite.hasNext()) {
visited = new boolean[vertices]; int adj = ite.next();
for (int i = 0; i < vertices; i+ if (!visited[adj])
+) DFS(adj);
adjLists[i] = new } }
DEPTH -FIRST SEARCH

public static void main(String args[]) {


Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);

System.out.println("Following is Depth First Traversal");

g.DFS(2);
}
}
DEPTH -FIRST SEARCH
Applications of DFS

• For an unweighted graph, DFS traversal of the graph produces the


minimum spanning tree.

• DFS can be used to detect a cycle in the graph

• We can specialize the DFS algorithm to find a path between the two
given vertices u and z.

• DFS can be used in topological sorting. Topological Sorting is mainly


used for scheduling jobs from the given dependencies among jobs

• DFS can be used to test if a graph is bipartite

• DFS can be used to finding Strongly connected components of a graph

• DFS can be used to solving puzzles with only one solution


https://learn.codemithra.com
THANK
YOU

+91 78150 [email protected] www.codemithra.com


95095

You might also like