Lab 6
Lab 6
Lab6:BFS
Tree Search vs Graph Search
Tree Search
Definition: A basic search algorithm for exploring possible states in a tree.
Key Characteristics:
Does not keep track of previously visited nodes (no memory of past
states).
Loop:
4. Otherwise, expand the node and add the new states to the frontier.
Graph Search
Definition: A refined search algorithm for exploring a graph.
Key Characteristics:
Lab6:BFS 1
Maintains an explored set: Keeps track of visited nodes to avoid re-
exploration.
Loop:
5. Expand the node and add new states to the frontier if they’re not
already in the explored set or frontier.
Key Characteristics:
FIFO queue: Nodes are explored in the order they’re added to the frontier.
Steps:
1. Start with the initial node and add it to the queue.
Mark it as visited.
Lab6:BFS 2
graph = {
'5' : ['3', '7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
Lab6:BFS 3
Step-by-Step Execution
1. Initialization:
3. Loop Execution:
Dequeue a Node: Remove the first element from the queue (FIFO).
For each unvisited neighbor, add it to the visited list and the queue .
Lab6:BFS 4
1. bfs() :
Inputs:
Outputs:
2. visited.append() :
3. queue.append() :
4. queue.pop(0) :
Lab Solution:
Graph Search and Path Reconstruction using BFS
Objective:
Analyze and represent the given undirected graph.
Problem Description:
The given map contains cities connected by undirected edges. Write a Python
program to represent the graph using an adjacency list or adjacency matrix.
Lab6:BFS 5
Output:
Represent the graph using the selected data structure.
graph = {
'A': ['B', 'C'],
'B': ['A'],
'C': ['A', 'D', 'E', 'F'],
'D': ['C'],
'E': ['C', 'J'],
'F': ['C', 'G'],
'G': ['F', 'L', 'M', 'N'],
'H': [],
'J': ['E', 'K'],
'K': ['J'],
'L': ['G'],
'M': ['G'],
Lab6:BFS 6
'N': ['G']
}
Objective:
Write a pseudocode for finding a path from city A to city K using Breadth-First
Search (BFS).
Objective:
Implement the BFS function to explore the graph.
Lab6:BFS 7
Store the parent of each visited node to assist in path reconstruction.
Requirements:
1. Receive the graph, initial state, and goal state as inputs.
3. Store the parent of each node in a suitable data structure (e.g., dictionary).
import queue
visited = set()
visited.add(start)
parent = {}
if current_node == goal:
return parent, True
start = 'A'
goal = 'K'
Lab6:BFS 8
parent, goal_reached = BFS(graph, start, goal)
if goal_reached:
print(f"\nThe goal '{goal}' was reached.")
else:
print(f"\nThe goal '{goal}' was NOT reached.")
Objective:
Implement the pathReconstruction() function to reconstruct the path from the
start to the goal state using the parent dictionary returned by BFS.
Lab6:BFS 9
node = parent.get(node, None)
return path
start = 'A'
goal = 'K'
parent, goal_reached = BFS(graph, start, goal)
Lab6:BFS 10