0% found this document useful (0 votes)
12 views20 pages

Group 8 Sudoku Project-2

This project report details the development of a C program to solve Sudoku puzzles using a backtracking algorithm. It outlines the problem domain, project description, system requirements, and various modules including input, validation, solving, output, and error handling. The report includes pseudocode, flowcharts, and complete code for each module, aiming to efficiently solve a standard 9x9 Sudoku grid.

Uploaded by

nahm63228
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)
12 views20 pages

Group 8 Sudoku Project-2

This project report details the development of a C program to solve Sudoku puzzles using a backtracking algorithm. It outlines the problem domain, project description, system requirements, and various modules including input, validation, solving, output, and error handling. The report includes pseudocode, flowcharts, and complete code for each module, aiming to efficiently solve a standard 9x9 Sudoku grid.

Uploaded by

nahm63228
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/ 20

PROJECT REPORT (CSN102)

A report submitted in partial fulfilment of the requirement for the course

Data Structures
Part of the degree of

BACHELOR OF COMPUTER SCIENCE AND ENGINEERING

Submitted to
Dr. Hemraj Saini
Assistant Professor
Submitted by:
Name-Mehul Sharma Roll no /SAP ID - 1000024979
Name-Adarsh Tripathi Roll no /SAP ID - 1000025774
Name-Sanya Srivastava Roll no /SAP ID - 1000024814
Name-Anukriti Singh Roll no /SAP ID - 1000025966
Section - A Group No.- 8

SCHOOL OF COMPUTING
DIT UNIVERSITY, DEHRADUN
(State Private University through State Legislature Act No. 10 of 2013 of Uttarakhand and approved by UGC)

Mussoorie Diversion Road, Dehradun, Uttarakhand - 248009, India.


April, 2025
CANDIDATES DECLARATION

I hereby certify that the work, which is being presented in the Report, entitled “Write the
algorithm and program for the Sudoku puzzle. Inputs: Given a partially filled 9×9 2D array ‘grid
[9][9]’, the goal is to assign digits (from 1 to 9) to the empty cells so that every row, column,
and subgrid of size 3×3 contains exactly one instance of the digits from 1 to 9”, in partial
fulfilment of the requirement as part of the course Data Structures of the Degree of Bachelor
of Computer Science and Engineering and submitted to the DIT University is an authentic
record of my work carried out during the period 06/01/2025 to 20/05/2025 under the guidance
of Dr.Hemraj Saini.

Date: Signature of the Candidate:

Student Name SAP ID Branch


TABLE OF CONTENT
CHAPTER PAGE No.

Introduction 1

Project Description 2

Each Module Of Project 3

Pseudocode and Flowchart of each 4


module/function

Data structure used to solve this Problem 5

Codes and outputs 6

Result analysis 7

Conclusion 8

Bibliography 9

Student Name SAP ID Branch


INTRODUCTION
Briefly describe the problem domain with suitable examples

Introduction

Sudoku is a logic-based, combinatorial number-placement puzzle that has gained widespread


popularity around the world. The objective of a standard Sudoku puzzle is to fill a 9×9 grid with
digits from 1 to 9 in such a way that each row, each column, and each of the nine 3×3 subgrids
(also called boxes or regions) contains all the digits from 1 to 9 exactly once. Some cells are pre-
filled to guide the player in solving the puzzle. The complexity of a Sudoku puzzle varies based
on the number and arrangement of these pre-filled digits.

Solving a Sudoku puzzle manually requires analytical thinking and patience. However,
automating the solution presents a well-known challenge in computer science — constraint
satisfaction problems. A constraint satisfaction problem (CSP) is a problem where the solution
must satisfy a number of constraints or conditions. Sudoku fits perfectly into this domain, as
each number placed in the grid must adhere to strict placement rules.

For instance, if a digit "5" is already present in the second row and the second column, placing
another "5" in the same row or column is invalid. Likewise, placing the same digit within the
same 3×3 box violates the puzzle's constraints. These logical conditions make Sudoku an ideal
problem to be solved using backtracking — a common recursive technique in programming.

This project focuses on creating a C program that reads a partially filled Sudoku grid and
attempts to solve it using backtracking, providing a fully solved grid as the output, or indicating
if no valid solution exists.

Student Name SAP ID Branch


Project Description
Purpose: This project aims to develop a program for the Sudoku puzzle. Inputs: Given a
partially filled 9×9 2D array ‘grid [9][9]’, the goal is to assign digits (from 1 to 9) to the empty
cells so that every row, column, and subgrid of size 3×3 contains exactly one instance of the
digits from 1 to 9.

Problem Statement:

The objective of this project is to develop a software application capable of solving a standard
9×9 Sudoku puzzle. The system should take a partially filled Sudoku grid as input and fill in the
missing values such that each row, each column, and each 3×3 subgrid contains all digits from 1
to 9 exactly once. The solver must use a systematic algorithm (such as backtracking) to ensure
accuracy and completeness of the solution. The application should be designed to handle valid
puzzles and output the solved grid efficiently.

System Requirements:

Hardware Requirements:

 Processor:Intel i3 or higher
 RAM: 4 GB minimum
 Hard Disk: 100 MB of free disk space
 Display: Standard display with minimum 1024×768 resolution
 Input Devices: Keyboard (for optional manual input)

Software Requirements:

 Operating System: Windows / Linux / macOS


 Programming Language: C++ (can also be implemented in Python or Java)
 Compiler: GCC / MinGW / Turbo C++ / Code::Blocks (or any IDE supporting C++)
 Optional:
o GUI framework (e.g., Qt for C++, Tkinter for Python) if user interface is needed.
o Text editor or IDE (e.g., VS Code, Code::Blocks)

Student Name SAP ID Branch


Modules of the Project
1. Input Module

Purpose: Takes input of the partially filled 9×9 Sudoku grid.


Features:

 Accepts user input via console or GUI


 Optional file input support
 Validates the initial grid for conflicts

2. Validation Module

Purpose: Checks whether placing a digit at a given cell is valid.


Features:

 Row check
 Column check
 3×3 Subgrid check

3. Solver Module (Backtracking Algorithm)

Purpose: Solves the puzzle recursively using the backtracking technique.


Features:

 Recursively fills each empty cell


 Backtracks when necessary
 Stops when puzzle is completely filled

4. Output Module

Purpose: Displays the solved grid.


Features:

 Console output or GUI-based display


 Optional save to file feature

5. Error Handling Module

Purpose: Handles invalid inputs or unsolvable puzzles.


Features:

 Displays appropriate error messages


 Prevents crashes due to incorrect input

Student Name SAP ID Branch


Pseudocode and Flowchart of Each Module
1. Input Module

Pseudocode
FUNCTION readInput(grid)
FOR i = 0 to 8
FOR j = 0 to 8
READ grid[i][j]
END FOR
END FOR
RETURN grid
END FUNCTION

Flowchart Description

 Start
 Loop through rows (i = 0 to 8)
o Loop through columns (j = 0 to 8)
 Input value into grid[i][j]
 End

2. Validation Module

Pseudocode
FUNCTION isSafe(grid, row, col, num)
FOR i = 0 to 8
IF grid[row][i] == num OR grid[i][col] == num
RETURN False
END FOR

startRow = row - row % 3


startCol = col - col % 3

FOR i = 0 to 2
FOR j = 0 to 2
IF grid[startRow + i][startCol + j] == num
RETURN False
RETURN True
END FUNCTION

Flowchart Description

 Start

Student Name SAP ID Branch


 Check if number exists in the same row or column
o If yes → Return False
 Check 3×3 subgrid
o If number exists → Return False
 Else → Return True
 End

3. Solver Module (Backtracking Algorithm)

Pseudocode
FUNCTION solveSudoku(grid)
FOR row = 0 to 8
FOR col = 0 to 8
IF grid[row][col] == 0
FOR num = 1 to 9
IF isSafe(grid, row, col, num)
grid[row][col] = num
IF solveSudoku(grid) == True
RETURN True
grid[row][col] = 0 // Backtrack
RETURN False
RETURN True
END FUNCTION

Flowchart Description

 Start
 Find first empty cell
 Loop num from 1 to 9
o Check if isSafe()
 If true → Place number and recurse
 If recursion fails → Backtrack
 If no number works → Return False
 If all cells filled → Return True
 End

4. Output Module

Pseudocode
FUNCTION printGrid(grid)
FOR i = 0 to 8
FOR j = 0 to 8
PRINT grid[i][j]
PRINT newline
END FUNCTION

Student Name SAP ID Branch


Flowchart Description

 Start
 Loop through each row and column
 Print each element
 Print newline after each row
 End

5. Error Handling Module

Pseudocode
FUNCTION checkGrid(grid)
IF any duplicate in row/column/box
PRINT "Invalid Puzzle"
RETURN False
RETURN True
END FUNCTION

Flowchart Description

 Start
 Scan rows, columns, subgrids
 If duplicate found → Show error
 Else → Proceed to solve
 End

Student Name SAP ID Branch


Data Structure Used to Solve the Problem
1. 2D Array

Description:

A 9×9 two-dimensional array is the primary data structure used to represent the Sudoku grid.
Each element in the array corresponds to a single cell in the Sudoku board. The array is typically
defined as int grid[9][9] in C++ or similar in other programming languages.

Purpose:

 Stores the initial puzzle configuration.


 Keeps track of all updates made during the solving process.
 Represents empty cells using the value 0 and filled cells using values from 1 to 9.

Example:
int grid[9][9] = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
...
};

Advantages:

 Simple and intuitive representation of the Sudoku board.


 Easy to iterate through rows, columns, and subgrids.
 Minimal memory usage and fast access time.

2. Boolean Arrays (For Optimization - Optional)

Description:

To improve the performance of the backtracking algorithm, three auxiliary boolean arrays are
sometimes used to track whether a specific number already exists in a row, column, or 3×3
subgrid.

Types:

 bool row[9][10] – Tracks numbers present in each row.


 bool col[9][10] – Tracks numbers present in each column.
 bool box[3][3][10] – Tracks numbers present in each 3×3 subgrid.

Student Name SAP ID Branch


Purpose:

 Speeds up the validation process (isSafe() function).


 Avoids repeated scanning of rows, columns, and boxes.

Advantages:

 Improves efficiency in large-scale Sudoku solvers.


 Allows constant time validation of constraints.

Student Name SAP ID Branch


C Code for Each Module
1. Input Module

Code
#include <stdio.h>

void readInput(int grid[9][9]) {


printf("Enter the Sudoku puzzle (use 0 for empty cells):\n");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
scanf("%d", &grid[i][j]);
}
}
}

2. Validation Module

Code
int isSafe(int grid[9][9], int row, int col, int num) {
// Check row and column
for (int i = 0; i < 9; i++) {
if (grid[row][i] == num || grid[i][col] == num)
return 0;
}

// Check 3x3 box


int startRow = row - row % 3;
int startCol = col - col % 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (grid[startRow + i][startCol + j] == num)
return 0;
}
}

return 1;
}

Student Name SAP ID Branch


3. Solver Module (Backtracking Algorithm)

Code
int solveSudoku(int grid[9][9]) {
int row, col;
int emptyFound = 0;

for (row = 0; row < 9; row++) {


for (col = 0; col < 9; col++) {
if (grid[row][col] == 0) {
emptyFound = 1;
break;
}
}
if (emptyFound) break;
}

if (!emptyFound)
return 1; // Puzzle Solved

for (int num = 1; num <= 9; num++) {


if (isSafe(grid, row, col, num)) {
grid[row][col] = num;
if (solveSudoku(grid))
return 1;
grid[row][col] = 0; // Backtrack
}
}

return 0; // Trigger backtracking


}

4. Output Module

Code
void printGrid(int grid[9][9]) {
printf("\nSolved Sudoku Puzzle:\n");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
printf("%d ", grid[i][j]);
}
printf("\n");
}
}

Student Name SAP ID Branch


5. Error Handling Module

Code
int isValidInitialGrid(int grid[9][9]) {
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
int num = grid[row][col];
if (num != 0) {
grid[row][col] = 0;
if (!isSafe(grid, row, col, num)) {
return 0;
}
grid[row][col] = num;
}
}
}
return 1;
}

6. Main Function (Driver Code)

Code
int main() {
int grid[9][9];

readInput(grid);

if (!isValidInitialGrid(grid)) {
printf("Invalid initial puzzle configuration.\n");
return 0;
}

if (solveSudoku(grid)) {
printGrid(grid);
} else {
printf("No solution exists for the given Sudoku puzzle.\n");
}

return 0;
}

Student Name SAP ID Branch


Complete Code and Output
Full C Code (Sudoku Solver)

#include <stdio.h>

// Function to read input grid


void readInput(int grid[9][9]) {
printf("Enter the Sudoku puzzle (use 0 for empty cells):\n");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
scanf("%d", &grid[i][j]);
}
}
}
// Function to print the Sudoku grid
void printGrid(int grid[9][9]) {
printf("\nSolved Sudoku Puzzle:\n");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
printf("%d ", grid[i][j]);
}
printf("\n");
}
}

// Check if a number can be placed in the given cell


int isSafe(int grid[9][9], int row, int col, int num) {
for (int i = 0; i < 9; i++) {
if (grid[row][i] == num || grid[i][col] == num)
return 0;
}

int startRow = row - row % 3;


int startCol = col - col % 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (grid[startRow + i][startCol + j] == num)
return 0;
}
}

return 1;
}

// Backtracking Sudoku solver

Student Name SAP ID Branch


int solveSudoku(int grid[9][9]) {
int row, col;
int emptyFound = 0;

for (row = 0; row < 9; row++) {


for (col = 0; col < 9; col++) {
if (grid[row][col] == 0) {
emptyFound = 1;
break;
}
}
if (emptyFound) break;
}

if (!emptyFound)
return 1; // Puzzle solved

for (int num = 1; num <= 9; num++) {


if (isSafe(grid, row, col, num)) {
grid[row][col] = num;
if (solveSudoku(grid))
return 1;
grid[row][col] = 0; // Backtrack
}
}

return 0;
}

// Function to check if initial puzzle is valid


int isValidInitialGrid(int grid[9][9]) {
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
int num = grid[row][col];
if (num != 0) {
grid[row][col] = 0;
if (!isSafe(grid, row, col, num)) {
return 0;
}
grid[row][col] = num;
}
}
}
return 1;
}

Student Name SAP ID Branch


// Main function
int main() {
int grid[9][9];

readInput(grid);

if (!isValidInitialGrid(grid)) {
printf("Invalid initial puzzle configuration.\n");
return 0;
}

if (solveSudoku(grid)) {
printGrid(grid);
} else {
printf("No solution exists for the given Sudoku puzzle.\n");
}

return 0;
}

Input

530070000
600195000
098000060
800060003
400803001
700020006
060000280
000419005
000080079

Output

Solved Sudoku Puzzle:


534678912
672195348
198342567
859761423
426853791
713924856
961537284
287419635
345286179

Student Name SAP ID Branch


Result Analysis
Execution Outcome

The Sudoku solver was tested with multiple input cases including standard, medium, and hard
puzzles. For all valid puzzles, the program correctly filled the empty cells while satisfying all
Sudoku constraints — no repetition in rows, columns, or 3×3 subgrids. If the input was
unsolvable or incorrect, the program promptly displayed a message indicating that no solution
exists. This confirms the reliability of the implemented logic.

Performance Evaluation

The algorithm follows a backtracking technique, which explores all possibilities in a structured
manner and retracts invalid paths efficiently. For puzzles with a unique solution and sufficient
clues, the program executed within a fraction of a second. Even in cases with sparse clues, the
solver completed execution without noticeable delay on a standard personal computer. Thus, the
program demonstrates efficient runtime performance for real-world applications.

Accuracy and Validity

 Each solution generated by the program was manually verified to be accurate.


 All solved puzzles followed the strict rules of Sudoku:
o Each row contained all digits from 1 to 9 without repetition.
o Each column contained all digits from 1 to 9 without repetition.
o Each 3×3 subgrid contained all digits from 1 to 9 without repetition.

This confirms that the output is correct and fully adheres to the rules of the game.

Observed Limitations
 The program does not handle puzzles with multiple solutions; it returns the first one it
finds.
 It expects all values between 0–9 as input. No advanced input validation is included for
out-of-range or non-numeric entries.
 The user interface is console-based; there is no graphical interface or puzzle generation
functionality.

Student Name SAP ID Branch


Conclusion
The Sudoku Puzzle Solver has been successfully designed and implemented using a
backtracking algorithm. The project fulfills its primary objective of solving any valid 9×9
Sudoku grid, where the user provides a partially filled puzzle. By applying constraint checks and
recursive logic, the solver efficiently fills in the empty cells without violating Sudoku rules.

Outcome

The program consistently returns correct solutions for solvable puzzles and clearly indicates
when no solution exists. It ensures that:

 Each digit from 1 to 9 appears exactly once in each row, column, and 3×3 subgrid.
 The input is processed correctly using a simple command-line interface.
 Users receive either a fully solved grid or a message explaining that the puzzle has no
solution.

The solver has been tested against multiple test cases and produced correct outputs, proving the
algorithm’s robustness and correctness. The solution demonstrates the effective use of recursion
and logic-based backtracking.

Final Remark

This project demonstrates how classical algorithms like backtracking can be applied to real-
world problems. The success of this implementation shows the power of structured problem-
solving techniques and lays the groundwork for further development, such as adding a graphical
interface, puzzle difficulty grading, or automated puzzle generation.

Student Name SAP ID Branch


Bibliography
1. Herbert Schildt, C: The Complete Reference, 4th Edition, McGraw-Hill Education,
2000.
Used for understanding C programming syntax, structure, and standard libraries.
2. E. Balagurusamy, Programming in ANSI C, 8th Edition, McGraw-Hill Education,
2019.
Referred for clarity on control structures, functions, and arrays in C.
3. GeeksforGeeks - https://www.geeksforgeeks.org/
Used for algorithm references, especially backtracking technique and Sudoku solver
logic.
4. Programiz - https://www.programiz.com/c-programming
Helped in understanding recursive functions and standard C programming
concepts.
5. Wikipedia - Sudoku - https://en.wikipedia.org/wiki/Sudoku
Referred for understanding Sudoku rules, structure, and puzzle-solving
constraints.
6. Stack Overflow - https://stackoverflow.com/
Utilized for resolving minor bugs and syntax clarifications during
development.

Student Name SAP ID Branch

You might also like