0% found this document useful (0 votes)
1K views6 pages

AD3311-AI Lab Manual-Ex1a and 1b

The document describes algorithms to solve the 8-puzzle and 8-queens problems using breadth-first search and depth-first search respectively. For the 8-puzzle problem, it defines initial and goal states, generates possible moves, and uses a BFS queue to find the shortest solution path. For 8-queens, it uses a depth-first search with backtracking to place queens without conflicts by recursively trying all row placements and returning on the first valid solution. Python programs implementing these algorithms are provided.

Uploaded by

kandocrush2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views6 pages

AD3311-AI Lab Manual-Ex1a and 1b

The document describes algorithms to solve the 8-puzzle and 8-queens problems using breadth-first search and depth-first search respectively. For the 8-puzzle problem, it defines initial and goal states, generates possible moves, and uses a BFS queue to find the shortest solution path. For 8-queens, it uses a depth-first search with backtracking to place queens without conflicts by recursively trying all row placements and returning on the first valid solution. Python programs implementing these algorithms are provided.

Uploaded by

kandocrush2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

EX. NO.

: 1 a)
IMPLEMENT BASIC SEARCH STRATEGIES – 8-PUZZLE PROBLEM

AIM:

To write a Python program to solve 8-puzzle problem by implementing basic search strategies.

ALGORITHM:

This algorithm uses a breadth-first search strategy, which guarantees finding the shortest path to the
goal state because it explores states level by level.

1. Define the goal state and the initial state of the 8-Puzzle.

2. Create an empty queue for BFS. Each element in the queue should consist of a state and its
corresponding path from the initial state.

3. Initialize the queue with the initial state and an empty path.

4. While the queue is not empty:

a. Dequeue the front element from the queue. This represents the current state and its path.

b. Check if the current state is the goal state:

- If it is, return the path as the solution.

c. If the current state is not the goal state:

- Generate all possible states that can be reached from the current state by moving the
blank tile (0) up, down, left, or right.

- For each possible state, ensure that it has not been visited before (to prevent
revisiting states and loops).

- Create a new path by appending the current possible state to the current path.

- Enqueue the possible state and its new path into the queue.

5. If the queue becomes empty and no solution is found, return that no solution exists.

3
PROGRAM:

from collections import deque

# Define the goal state and initial state


goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] # 0 represents the blank tile

# You can modify the initial state as needed


initial_state = [[1,2,3], [0,4,6], [7, 5,8]] # Example initial state

# Function to check if a state is the goal state


def is_goal(state):
return state == goal_state

# Function to get possible moves from the current state


def get_possible_moves(state):
moves = []
blank_row, blank_col = None, None

for i in range(3):
for j in range(3):
if state[i][j] == 0:
blank_row, blank_col = i, j

# Define possible moves (up, down, left, right)


moves_delta = [(1, 0), (-1, 0), (0, 1), (0, -1)]

for delta in moves_delta:


new_row, new_col = blank_row + delta[0], blank_col + delta[1]

if 0 <= new_row < 3 and 0 <= new_col < 3:


new_state = [row[:] for row in state]
new_state[blank_row][blank_col], new_state[new_row][new_col] =
new_state[new_row][new_col], new_state[blank_row][blank_col]
moves.append(new_state)

return moves

# Breadth-First Search function


def bfs(initial_state):
queue = deque([(initial_state, [])]) # Each element in the queue is a state and its path

while queue:
current_state, path = queue.popleft()

if is_goal(current_state):
return path

4
for move in get_possible_moves(current_state):
if move not in path: # Prevent revisiting states to avoid loops
new_path = path + [move]
queue.append((move, new_path))

return None # No solution found

# Run BFS to solve the puzzle


solution_path = bfs(initial_state)

# Print the solution path


if solution_path:
print("Solution Steps:")
for step in solution_path:
for row in step:
print(row)
print()
else:
print("No solution found.")

OUTPUT:

RESULT:

Thus, a Python program is successfully written and executed to solve 8-puzzle problem by implementing
BFS algorithm.

5
EX. NO.: 1 b)
IMPLEMENT BASIC SEARCH STRATEGIES – 8-QUEENS PROBLEM

AIM:
To write a Python program to solve 8-queens problem by implementing basic search strategies.

ALGORITHM:

The algorithm uses depth-first search and backtracking to explore all possible combinations of queen
placements while ensuring no two queens threaten each other.

1. Define the is_safe function:

- Check if there is a queen in the same row:

➢ Iterate through all columns to the left of col.

➢ If any cell in the same row as row and in a column to the left of col contains a queen
(board[row][i] == 1), return False.

- Check the upper diagonal on the left:

➢ Iterate through rows from row to 0 (inclusive) and columns from col to 0 (inclusive).

➢ If any cell in the upper left diagonal contains a queen (board[i][j] == 1), return False.

- Check the lower diagonal on the left:

➢ Iterate through rows from row to the last row (inclusive) and columns from col to 0
(inclusive).

➢ If any cell in the lower left diagonal contains a queen (board[i][j] == 1), return False.

- If no conflicts are found, return True as it's safe to place a queen.

2. Define the solve_queens function:

- Base Case: If col equals the width of the board (8 in this case), return True as all queens are
placed successfully.

- Iterate through each row (from 0 to 7) in the current column col:

➢ Check if it's safe to place a queen at board[row][col] using the is_safe function.

➢ If it's safe, mark board[row][col] as 1 (place a queen).

6
➢ Recursively call solve_queens with the next column col + 1.

➢ If the recursive call returns True, return True to propagate the success up the call stack.

➢ If the recursive call returns False, backtrack by setting board[row][col] back to 0 and
continue the loop.

- If no safe position is found in the current column, return False.

3. Define the print_solution function:

- Print the board with queens placed as "Q" and empty cells as ".".

4. Define the solve_8_queens function:

- Initialize an empty 8x8 chessboard called board with all zeros.

- Call the solve_queens function with board and col = 0.

- If solve_queens returns True, call the print_solution function to print the solution.

- If solve_queens returns False, print "No solution exists."

5. Call the solve_8_queens function to solve the 8-Queens problem.

PROGRAM:

def is_safe(board, row, col):


# Check if a queen can be placed at board[row][col] safely
# Check the row on the left
for i in range(col):
if board[row][i] == 1:
return False

# Check upper diagonal on the left


for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False

# Check lower diagonal on the left


for i, j in zip(range(row, len(board), 1), range(col, -1, -1)):
if board[i][j] == 1:
return False

return True

def solve_queens(board, col):


# Base case: All queens are placed
if col == len(board):
7
return True

for i in range(len(board)):
if is_safe(board, i, col):
board[i][col] = 1 # Place queen
if solve_queens(board, col + 1): # Recur for next column
return True
board[i][col] = 0 # If placing queen doesn't lead to a solution, backtrack

return False

def print_solution(board):
for row in board:
print(" ".join(["Q" if cell == 1 else "." for cell in row]))

def solve_8_queens():
board = [[0 for _ in range(8)] for _ in range(8)]

if not solve_queens(board, 0):


print("No solution exists.")
else:
print_solution(board)

solve_8_queens()

OUTPUT:

RESULT:

Thus, a Python program is successfully written and executed to solve 8-queens problem by implementing
DFS and backtracking.

You might also like