0% found this document useful (0 votes)
24 views14 pages

Sudoku Solver Project

Uploaded by

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

Sudoku Solver Project

Uploaded by

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

SUDOKU SOLVER

21CSS101J- PROGRAMMING FOR PROBLEM SOLVING


A CASE STUDY REPORT

Submitted by

PARTHIV D PRABHU RA2411003020864


ARUNKUMAR RA2411003020869
AMITRAJEET PAUL RA2411003020886

I SEMESTER/ I YEAR

COMPUTER SCIENCE AND ENGINEERING

FACULTY OF ENGINEERING AND TECHNOLOGY

SRM INSTITUTE OF SCIENCE AND TECHNOLOGY


RAMAPURAM, CHENNAI
NOVEMBER 2024
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
(Deemed to be University U/S 3 of UGC Act, 1956)

BONAFIDE CERTIFICATE

Certified that this project report titled PEER TO PEER CHAT APPLICATION is
the bonafide work of Mr. PARTHIV D PRABHU (RA241100302084),
Mr.ARUNKUMAR RATHINASABAPATHI ,(RA2411003020864)
Mr.AMITRAJEET PAUL (RA2411003020864 ) who carried out the project work
under my supervision. This Case study work confirms to 21CSS101J-
PROGRAMMING FOR PROBLEM SOLVING , I Semester, I year, 2024-2025
ODD Semester.

SIGNATURE
Dr.J.JOSPIN JEYA, M. E, Ph.D.,
Assistant Professor
Computer Science and Engineering,
SRM Institute of Science and Technology,
Ramapuram, Chennai.
TABLE OF CONTENT
S. No Content Page Number

1 Introduction

2 System Specification
2.1 Hardware Specification
2.2 Software Specification
3 Flow Diagram / Architecture Diagram
(Flowchart/algorithm)
4 Explanation of the working methodology

5 Source code

6 Output

7 Conclusion

8 References

.
INTRODUCTION OF THE PROJECT

PROBLEM STATEMENT:
The problem involves designing a program to generate and solve
Sudoku puzzles. A Sudoku puzzle is a 9x9 grid divided into nine 3x3
sub-grids, where some cells contain numbers (1-9) while others are
empty. The goal is to fill the grid such that each row, column, and 3x3
sub-grid contains unique numbers from 1 to 9. The program needs to
generate a valid puzzle with a unique solution and implement a
backtracking algorithm to solve it. Additionally, the grid must be
displayed in a formatted table for user readability.
SYSTEM REQUIREMENTS

Operating System Windows 10

Processor IntelR Core™ i5-2400 CPU @


3.10GHz (4 CPUs), ~3.1GHz
Memory 4096MB RAM

Available OS Memory 3978MB RAM

Software Python IDLE, Pycharm


ARCHITECTURE DIAGRAM
1. Initialize Environment
o Import necessary libraries: random for number shuffling, copy for deep
copying grids, and tabulate for displaying grids in a formatted table.
o Define the grid size N = 9.
2. Grid Display Function (print_grid)
o Convert zeros (empty cells) in the grid to blank spaces for better
readability.
o Display the grid using the tabulate library with a formatted table.
3. Validation Function (isSafe)
o Check if a number can be placed at a given cell:
 Ensure the number is not already present in the same row or
column.
 Check the corresponding 3x3 sub-grid for duplicates.
o Return True if the placement is valid; otherwise, return False.
4. Sudoku Solver (solveSudoku)
o If the current cell is beyond the last column, move to the next row.
o If the current cell already contains a number, proceed to the next cell.
o Try placing numbers (1-9) in the cell:
 Use isSafe to validate the placement.
 Recursively call solveSudoku for the next cell.
 If the grid cannot be solved, backtrack by resetting the cell to 0.
o Return True if solved; otherwise, return False.
5. Generate Full Grid (generate_full_grid)
o Create an empty 9x9 grid.
o Recursively fill each cell with random numbers (1-9) using the is_valid
function to ensure validity.
6. Find Empty Cell (find_empty)
o Iterate through the grid to locate the first cell containing 0 (empty cell).
o Return the cell’s position or None if no empty cell exists.
7. Remove Cells to Create Puzzle (remove_cells)
o Shuffle all cell positions and remove numbers one by one, testing grid
solvability after each removal:
 If removing a number makes the puzzle unsolvable or creates
multiple solutions, restore the number.
8. Generate Sudoku Puzzle (generate_sudoku)
o Use generate_full_grid to create a complete, valid grid.
o Call remove_cells to remove numbers and create a puzzle with a unique
solution.
9. Main Execution
o Generate a Sudoku puzzle using generate_sudoku.
o Print the generated puzzle using print_grid.
o Solve the puzzle using solveSudoku and print the solution, or indicate
that no solution exists.
10. End of Program
o The program ensures a playable puzzle is generated, solves it, and displays
the result in a user-friendly format.
EXPLANATION

The code is a Python program that generates and solves Sudoku


puzzles using backtracking and recursive algorithms. It begins by
importing necessary modules like random for shuffling numbers
during grid generation, copy for maintaining separate puzzle states,
and tabulate for rendering the grid in a table format. The program
defines several helper functions, starting with print_grid, which
formats the Sudoku grid for display by replacing zeros (empty cells)
with blank spaces. The isSafe function ensures a number can be safely
placed in a cell by checking its row, column, and corresponding 3x3
sub-grid. The solveSudoku function employs backtracking to fill
empty cells recursively until the grid is solved or deemed unsolvable.
To generate puzzles, find_empty locates unfilled cells, and is_valid
checks if a number can be inserted at a specific position. The
generate_full_grid function creates a complete, valid Sudoku grid by
recursively filling cells with randomized numbers, ensuring all
constraints are met. Once a full grid is generated, remove_cells
strategically removes numbers to create a puzzle while ensuring that
the resulting puzzle has a unique solution, validated using the solve
function. The generate_sudoku function integrates these steps to
produce a playable puzzle. In the main section, the program generates
a puzzle, prints it, solves it using solveSudoku, and displays the
solved grid or indicates that no solution exists. The structured
approach ensures Sudoku puzzles are both challenging and solvable.
SOURCE CODE

import random
import copy
import tabulate
N=9

# Helper to print Sudoku grid with formatting


def print_grid(grid):
GRID2=[]
for row in grid:
R=[]
for num in row:
if num==0:
R.append(" ")
else:
R.append(num)
GRID2.append(R)
print(tabulate.tabulate(GRID2,tablefmt="fancy_grid"))

# Solver's isSafe function


def isSafe(grid, row, col, num):
# Check row
for x in range(9):
if grid[row][x] == num:
return False
# Check column
for x in range(9):
if grid[x][col] == num:
return False
# Check 3x3 sub-grid
startRow = row - row % 3
startCol = col - col % 3
for i in range(3):
for j in range(3):
if grid[i + startRow][j + startCol] == num:
return False
return True

# Backtracking solver
def solveSudoku(grid, row=0, col=0):
if row == N - 1 and col == N:
return True
if col == N:
row += 1
col = 0
if grid[row][col] > 0:
return solveSudoku(grid, row, col + 1)
for num in range(1, N + 1):
if isSafe(grid, row, col, num):
grid[row][col] = num
if solveSudoku(grid, row, col + 1):
return True
grid[row][col] = 0
return False

# Sudoku puzzle generation


def find_empty(grid):
for i in range(9):
for j in range(9):
if grid[i][j] == 0:
return (i, j)
return None

def is_valid(grid, num, pos):


row, col = pos
if num in grid[row]:
return False
for i in range(9):
if grid[i][col] == num:
return False
box_x = col // 3
box_y = row // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if grid[i][j] == num:
return False
return True

def solve(grid, count=0):


empty = find_empty(grid)
if not empty:
return count + 1
row, col = empty
for num in range(1, 10):
if is_valid(grid, num, (row, col)):
grid[row][col] = num
count = solve(grid, count)
if count > 1:
break
grid[row][col] = 0
return count

def generate_full_grid():
grid = [[0 for _ in range(9)] for _ in range(9)]
def fill_grid(grid):
empty = find_empty(grid)
if not empty:
return True
row, col = empty
numbers = list(range(1, 10))
random.shuffle(numbers)
for num in numbers:
if is_valid(grid, num, (row, col)):
grid[row][col] = num
if fill_grid(grid):
return True
grid[row][col] = 0
return False
fill_grid(grid)
return grid

def remove_cells(grid, attempts=5):


grid = copy.deepcopy(grid)
cells = [(i, j) for i in range(9) for j in range(9)]
random.shuffle(cells)
for (row, col) in cells:
backup = grid[row][col]
grid[row][col] = 0
grid_copy = copy.deepcopy(grid)
solution_count = solve(grid_copy)
if solution_count != 1:
grid[row][col] = backup
return grid

def generate_sudoku():
full_grid = generate_full_grid()
puzzle = remove_cells(full_grid)
return puzzle

# Main execution
if __name__ == "__main__":
# Generate a Sudoku puzzle
sudoku_puzzle = generate_sudoku()
print("Generated Sudoku Puzzle:")
print_grid(sudoku_puzzle)

# Solve the generated Sudoku puzzle


print("\nSolved Sudoku Grid:")
if solveSudoku(sudoku_puzzle):
print(tabulate.tabulate(sudoku_puzzle,tablefmt="fancy_grid"))
else:
print("No solution exists")
SCREENSHOT
CONCLUSION

This Sudoku project successfully combines algorithmic problem-


solving with practical implementation, offering a complete solution
for generating and solving Sudoku puzzles. The project leverages
recursive backtracking for solving puzzles and randomization
techniques for generating valid grids with unique solutions. It ensures
user engagement by formatting the puzzles for clear visual
representation using the tabulate library. By integrating grid
validation, constraint satisfaction, and uniqueness checks, the project
demonstrates the complexity and elegance of algorithm design in
recreational mathematics. Overall, it serves as a robust foundation for
exploring advanced Sudoku variations, optimization techniques, and
further applications of constraint satisfaction problems in computer
science.
REFERENCES
https://www.geeksforgeeks.org/sudoku-backtracking-7/
https://www.sudoku-solutions.com/
https://www.sudoku9x9.com/sudokusolver/
https://sudoku.com/

You might also like