0% found this document useful (0 votes)
2 views6 pages

EXP3

The document describes an experiment implementing a Sudoku solver using the A* search algorithm, detailing the problem definition, theory, and algorithm specifics. It outlines the state representation, initial and goal states, operators, heuristic and cost functions, and the A* search process. The analysis concludes that A* is complete and optimal for solving Sudoku, with manageable time complexity but exponential space complexity.

Uploaded by

rpadvi2003
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)
2 views6 pages

EXP3

The document describes an experiment implementing a Sudoku solver using the A* search algorithm, detailing the problem definition, theory, and algorithm specifics. It outlines the state representation, initial and goal states, operators, heuristic and cost functions, and the A* search process. The analysis concludes that A* is complete and optimal for solving Sudoku, with manageable time complexity but exponential space complexity.

Uploaded by

rpadvi2003
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

EXPERIMENT-3

Name: Tathagat Sengupta


Uid: -2021300110
Problem Definition: Implement a Sudoku problem using the Informed searching
technique using A*. Analyze the algorithm with respect to Completeness, Optimality, time
and space Complexity

Theory:
Using the A* search algorithm to solve the Sudoku problem is an interesting approach. A* is
an informed searching technique that combines elements of both breadth-first search and
best-first search. It uses a heuristic function to estimate the cost to reach the goal from a
given state and maintains a priority queue to explore nodes in a way that minimizes this
estimated cost. Let's break down how A* can be applied to solve Sudoku and analyse its
properties.

Sudoku Problem: Sudoku is a number-placement puzzle where the objective is to fill a 9x9
grid with digits so that each column, each row, and each of the nine 3x3 subgrids (called
"regions") contain all of the digits from 1 to 9. The puzzle starts with some cells already
filled, and the goal is to fill in the remaining cells while adhering to the Sudoku rules.

A* Algorithm for Sudoku:

1. State Representation: In the context of Sudoku, a state represents a partially filled


Sudoku grid.

2. Initial State: The initial state is the given Sudoku puzzle.

3. Goal State: The goal state is a completely filled Sudoku grid that adheres to the Sudoku
rules.

4. Operators: The operators in Sudoku are choosing a row, column, and digit to place in a
cell that is currently empty while ensuring it doesn't violate Sudoku rules.

5. Heuristic Function (h): A* requires a heuristic function that estimates the cost from the
current state to the goal. In Sudoku, a common heuristic is to count the number of empty
cells in the current state. This heuristic is admissible because it never overestimates the
true cost to the goal, as filling in an empty cell will reduce the count.

6. Cost Function (g): The cost function measures the actual cost from the initial state to the
current state. In Sudoku, the cost can be the number of steps (moves) taken to reach the
current state.

Dept of Computer Engineering., Sardar Patel Institute of Technology, Andheri (West) Page 1
7. A* Search: A* maintains a priority queue of states to explore. At each step, it selects the
state with the lowest f(n) value, where f(n) = g(n) + h(n). It expands the selected state by
applying valid operators and adds resulting states to the queue.

In conclusion, using A* with an admissible heuristic to solve Sudoku is a complete and


optimal approach, ensuring it will find the shortest path to a solution. The time complexity
can be manageable with a good heuristic, although the worst-case space complexity
remains exponential due to the nature of the puzzle.

Code:

import heapq
import time

total_steps = 0

def is_valid(board, row, col, num):

for i in range(4):
if board[row][i] == num or board[i][col] == num:
return False

start_row, start_col = 2 * (row // 2), 2 * (col // 2)


for i in range(start_row, start_row + 2):
for j in range(start_col, start_col + 2):
if board[i][j] == num:
return False

return True

def heuristic(board):

return sum(1 for row in board for cell in row if cell == 0)

def solve_sudoku(board):
global total_steps
intermediate_states = []

priority_queue = [(heuristic(board), board)]

Dept of Computer Engineering., Sardar Patel Institute of Technology, Andheri (West) Page 2
while priority_queue:
estimated_cost, current_board = heapq.heappop(priority_queue)
empty_cells = [(i, j) for i in range(4) for j in range(4) if
current_board[i][j] == 0]

if not empty_cells:

return current_board, intermediate_states

row, col = empty_cells[0]

for num in range(1, 5):


if is_valid(current_board, row, col, num):
new_board = [row[:] for row in current_board]
new_board[row][col] = num
priority = heuristic(new_board)
heapq.heappush(priority_queue, (priority, new_board))
total_steps += 1

intermediate_states.append(new_board)

return None, intermediate_states

def get_user_input():
sudoku_board = []
print("Enter the Sudoku puzzle (4x4 grid):")
for i in range(4):
row = input(f"Enter values for row {i + 1} separated by spaces:
").split()
if len(row) != 4:
print("Invalid input. Please enter 4 values for each row.")
return None
row = [int(cell) if cell.isdigit() else 0 for cell in row]
sudoku_board.append(row)
return sudoku_board

user_input_board = get_user_input()

if user_input_board:

Dept of Computer Engineering., Sardar Patel Institute of Technology, Andheri (West) Page 3
start_time = time.time()
solution, intermediate_states = solve_sudoku(user_input_board)
end_time = time.time()

if solution:
print("Solution Found:")
for row in solution:
print(row)
else:
print("No solution found.")

print(f"Total Steps Taken: {total_steps}")

execution_time = end_time - start_time


print(f"Execution time: {execution_time:.6f} seconds")

print("\nIntermediate States:")
for i, state in enumerate(intermediate_states):
print(f"Step {i + 1}:")
for row in state:
print(row)
print()

Output:

Dept of Computer Engineering., Sardar Patel Institute of Technology, Andheri (West) Page 4
Dept of Computer Engineering., Sardar Patel Institute of Technology, Andheri (West) Page 5
Dept of Computer Engineering., Sardar Patel Institute of Technology, Andheri (West) Page 6

You might also like