bfs_dfs
bfs_dfs
Program 2
Date: 27/08/24
AIM: Program to implement best first search and depth first search.
DESCRIPTION:
BFS:
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a
node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are
traversed. This is different from DFS in a way that closest vertices are visited before others.
We mainly traverse vertices level by levelBFS itself can be used to detect cycle in a directed
and undirected graph, find shortest path in an unweighted graph and many more problems.
DFS:
Depth First Traversal (or DFS) is a traversal technique which involves the idea of recursion
and backtracking. DFS goes in-depth, i.e., traverses all nodes by going ahead, and when there
are no further nodes to traverse in the current path, then it backtracks on the same path and
traverses other unvisited nodes.
ALGORITHM:
Breadth-First Search (BFS) Algorithm:
1. Step 1: Start at the given node, mark it as visited, and enqueue it.
2. Step 2: While the queue is not empty, repeat Steps 3 to 5.
3. Step 3: Dequeue a node from the front of the queue.
4. Step 4: Visit and mark all unvisited adjacent nodes of the dequeued node, then
enqueue them.
5. Step 5: Continue this process until all nodes have been visited or the queue is empty.
Depth-First Search (DFS) Algorithm:
1. Step 1: Start at the given node and mark it as visited.
2. Step 2: Visit an unvisited adjacent node of the current node.
3. Step 3: Mark this new node as visited and move to it.
4. Step 4: Repeat Steps 2 and 3 until there are no unvisited adjacent nodes.
5. Step 5: Backtrack to the previous node and repeat the process until all nodes have
been visited.
SOURCE CODE:
BFS:-
from collections import defaultdict, deque
class Graph:
def __init__(self):
self.graph = defaultdict(list)
while q:
s = q.popleft()
print(s, end=" ")
for i in self.graph[s]:
if i not in visited:
q.append(i)
visited.add(i)
if __name__ == '__main__':
g = Graph()
DFS:-
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
if __name__ == '__main__':
g = Graph()
for _ in range(num_edges):
u, v = input("Enter the edge (u v): ").split()
g.addEdge(u, v)
OUTPUT:
BFS-
DFS-