PRACTICAL - 6
A- Write a program to solve Missionaries and Cannibals
problem.
CODE –
def is_valid_state(m1, c1, m2, c2):
return (m1 >= 0 and m1 <= 3 and c1 >= 0 and c1 <= 3 and
m2 >= 0 and m2 <= 3 and c2 >= 0 and c2 <= 3 and
(m1 == 0 or m1 >= c1) and (m2 == 0 or m2 >= c2))
def get_possible_moves(m1, c1, m2, c2):
moves = []
boat_moves = [(1, 0), (2, 0), (0, 1), (0, 2), (1, 1)]
for m, c in boat_moves:
if (m1 >= m and c1 >= c) and is_valid_state(m1 - m, c1 - c, m2 + m, c2 + c):
[Link]((m, c))
return moves
def bfs_solution():
initial_state = (3, 3, 0, 0)
goal_state = (0, 0, 3, 3)
queue = [(initial_state, [])]
visited = set()
[Link](initial_state)
while queue:
(m1, c1, m2, c2), path = [Link](0) # Removing the first element
if (m1, c1, m2, c2) == goal_state:
return path
for m, c in get_possible_moves(m1, c1, m2, c2):
new_state = (m1 - m, c1 - c, m2 + m, c2 + c)
if new_state not in visited:
[Link](new_state)
[Link]((new_state, path + [(m, c)]))
return None
def print_solution(path):
if path is None:
print("No solution found")
return
state = (3, 3, 0, 0)
print("Initial State: (3, 3, 0, 0)")
for move in path:
m, c = move
new_state = (state[0] - m, state[1] - c, state[2] + m, state[3] + c)
print(f"Move {m} missionaries and {c} cannibals from left to right.")
print(f"State: {new_state}")
state = new_state
print("Goal State: (0, 0, 3, 3)")
if __name__ == "__main__":
path = bfs_solution()
print_solution(path)
OUTPUT:-
B- Design an application to simulate number puzzle problem.
CODE-
From collections import deque
From typing import List, Tuple, Optional
# Define the goal state
GOAL_STATE = (1, 2, 3, 4, 5, 6, 7, 8, 0)
# Direction vectors for moving tiles (Up, Down, Left, Right)
MOVES = [(-1, 0), (1, 0), (0, -1), (0, 1)]
Def get_neighbors(state: Tuple[int, …]) -> List[Tuple[int, …]]:
“””Generate possible moves from the current state.”””
Index = [Link](0)
X, y = divmod(index, 3)
Neighbors = []
For dx, dy in MOVES:
New_x, new_y = x + dx, y + dy
If 0 <= new_x < 3 and 0 <= new_y < 3:
New_index = new_x * 3 + new_y
New_state = list(state)
New_state[index], new_state[new_index] = new_state[new_index],
new_state[index]
[Link](tuple(new_state))
Return neighbors
Def bfs_solver(start: Tuple[int, …]) -> Optional[List[Tuple[int, …]]]:
“””Solve the puzzle using the BFS algorithm.”””
Queue = deque([(start, [])])
Explored = set()
While queue:
Current, path = [Link]()
If current == GOAL_STATE:
Return path + [current]
If current in explored:
Continue
[Link](current)
For neighbor in get_neighbors(current):
If neighbor not in explored:
[Link]((neighbor, path + [current]))
Return None
Def print_puzzle(state: Tuple[int, …]):
“””Print the puzzle state.”””
For I in range(0, 9, 3):
Print(‘ ‘.join(str(x) if x != 0 else ‘.’ For x in state[i:i+3]))
Print()
Def main():
# Initial state of the puzzle
Initial_state = (1, 2, 3, 4, 5, 6, 7, 0, 8)
Print(“Initial Puzzle State:”)
Print_puzzle(initial_state)
# Solve the puzzle
Solution = bfs_solver(initial_state)
If solution:
Print(“Solution Path:”)
For step in solution:
Print_puzzle(step)
Else:
Print(“No solution found.”)
If __name__ == “__main__”:
Main()
OUTPUT:-