Professional Documents
Culture Documents
: 50
Experiment No. - 03
Aim: Program on uninformed search methods (DFS and BFS).
Theory:
Breadth-First Search (BFS):
Objective: BFS explores a graph or tree level by level, visiting all nodes at the current level before moving
on to the next level.
Data Structure: It uses a queue to keep track of the nodes to be visited.
Order of Visiting Nodes: BFS starts at the root (or any specified node) and visits all its neighbors before
moving on to the next level. It proceeds in a breadthward motion.
Completeness: BFS is complete for finite graphs and trees. It will always find a solution if one exists.
Memory Usage: It tends to use more memory compared to DFS as it needs to store all nodes at the current
level.
Algorithm:
Breadth-First Search (BFS) Algorithm:
1. Create an empty queue and enqueue the start node.
2. Create a set to track visited nodes.
3. While the queue is not empty:
- Dequeue a node from the queue.
- Mark the node as visited.
- Process the node (print or store in the path).
- Enqueue all unvisited neighbors of the current node.
4. Repeat until the queue is empty or the goal node is reached.
Depth-First Search (DFS) Algorithm:
1. Create an empty stack and push the start node onto it.
2. Create a set to track visited nodes.
3. While the stack is not empty:
- Pop a node from the stack.
- Mark the node as visited.
- Process the node (print or store in the path).
- Push all unvisited neighbors of the current node onto the stack.
4. Repeat until the stack is empty or the goal node is reached.
Program:
1 . Breadth-First Search (BFS):
graph = {
'S' : ['A','B','C'],
'A' : ['D', 'E'],
'B' : [],
'C' : ['F','G'],
'D' : [],
'E' : ['H','I'],
'F' : [],
'G' : [],
'H' : [],
'I' : [],
}
if current_node == goal:
print(f"\nGoal node {goal} reached.")
break
# Driver Code
start_node = 'S'
goal_node = 'G'
print(f"Following is the Breadth-First Search from {start_node} to
{goal_node}:")
bfs(visited, graph, start_node, goal_node) # function calling
Output:
if node == goal:
print("Following is the Depth-First Search path:")
print(' '.join(path))
print(f"Goal node {goal} reached.")
return
visited.add(node)
# Driver Code
start_node = 'S'
goal_node = 'G'
dfs(graph, start_node, goal_node)
Output:
Conclusion: Breadth-First Search (BFS) and Depth-First Search (DFS) algorithms were
implemented to traverse a node graph, providing a path from the start node 'S' to the goal node 'G'.