17-BFS, DFS-05-02-2025
17-BFS, DFS-05-02-2025
BREADTH-FIRST SEARCH
INTRODUCTION
1. Visited
2. Not Visited
• Take the front item of the queue and add it to the visited
list.
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
bfs.java
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.BFS(2);
}
}
BREADTH-FIRST SEARCH
Applications of BFS
▪ BFS can be used to find the neighboring locations from a given source
location.
▪ 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.
1. Visited
2. Not Visited
• Take the top item of the stack and add it to the visited
list.
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
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.DFS(2);
}
}
DEPTH -FIRST SEARCH
Applications of DFS
• We can specialize the DFS algorithm to find a path between the two
given vertices u and z.