You are on page 1of 19

1

SUDOKU GAME USING C++

ABSTRACT:

Sudoku game is well famous and popular game among many players all over the world.
This report details the development of a Sudoku game application that is written in Java. The
application is even developed to work in Android systems. In addition, the report details the
implementation of the complexity of the algorithms used to solve any kind of Sudoku puzzle. Also,
how to generate a puzzle with different level of difficulties and make sure there will be only one
solution. The aim of the report is also to discuss the backtracking, brute force algorithms and other
logics in order to create and solve Sudoku puzzles. Furthermore, the user-friendly environment is
considered in the report as the rules of Sudoku are connected to the interface. Moreover, the report
specifics how well these methods of solving solves the puzzle and achieved the goal of this
implementation. The report concludes by evaluating the end application to analyse how good it
met its objectives and the performance of solving algorithms. Finally, the report summarises the
overall achievements of the application development and indicates other possible extensions

This project aims to develop a Sudoku game and solver implemented in C++. The game
allows players to interactively solve Sudoku puzzles through a command-line interface. The solver
component utilizes backtracking algorithm to efficiently find solutions to Sudoku puzzles. The
game provides options for generating new puzzles of varying difficulties, allowing players to
challenge themselves with puzzles of increasing complexity. Additionally, the game includes
features such as input validation, error detection, and a timer to track solving duration. The project
demonstrates fundamental programming concepts such as data structures, algorithms, and user
input/output handling in C++.

EXISTING SYSTEM:
2

Sudoku is a logic-based combinatorial number-placement puzzle. In C++, you can


implement a Sudoku solver using various algorithms like backtracking, constraint propagation,
or brute-force methods. Here's a general outline of how you could approach it:

❖ :Data Structure: Represent the Sudoku grid using a 2D array or a custom data structure to
store the numbers.

❖ Input: Read the Sudoku puzzle from a file or accept input from the user.

❖ Validation: Ensure that the initial puzzle is valid, meaning it follows the rules of Sudoku
(no repeated numbers in rows, columns, or 3x3 subgrids)

❖ .Solver Algorithm: Implement the solving algorithm. Backtracking is a common approach


where you recursively try placing numbers and backtrack when a conflict arises

❖ Output: once solved, display the solved puzzle to the user.

❖ Displaying the Grid: You need to display the Sudoku grid to the user. This can be done
using the console or a graphical user interface (GUI) library like SFML or Qt.

❖ Input Handling: Allow the user to interact with the grid by entering numbers to fill in the
empty cells. Ensure that the input is valid and follows Sudoku rules.

❖ Game Logic: Implement the game logic to check if the user's input is correct and if the
puzzle is solved

❖ .Generating Puzzles: You can either create puzzles manually or generate them
programmatically. Generating puzzles algorithmically involves creating a complete
Sudoku grid and then removing numbers while ensuring the puzzle remains solvable.
3

❖ Win Condition: Define conditions for winning the game, such as when the puzzle is solved
correctly.

PROPOSED SYSTEM:

A proposed system for implementing Sudoku in C++ could involve several key
components. First, you would need a data structure to represent the Sudoku grid, which could be
4

a two-dimensional array or a custom class to encapsulate the grid's functionality. This structure
would store the numbers in the grid and provide methods for accessing and modifying them.

Next, you would need functions to validate whether a given number can be placed
in a specific cell according to the rules of Sudoku. These rules state that each row, column, and
3x3 subgrid must contain the numbers 1 through 9 without repetition.

Additionally, you would implement functions for solving the Sudoku puzzle, such as
backtracking algorithms or other strategies like constraint propagation. These algorithms would
systematically fill in empty cells while ensuring that the puzzle remains valid at each step.

To interact with the Sudoku grid, you could create a user interface allowing players
to input numbers, display the current state of the puzzle, and receive feedback on their progress.
This interface could be text-based or graphical, depending on the desired level of complexity.

Overall, the system would consist of a data structure to represent the Sudoku grid,
functions to enforce the rules of the game, algorithms for solving the puzzle, and a user interface
for interaction. By combining these elements, you could create a robust and efficient Sudoku solver
and game platform in C++.

Throughout this article, by "possibilities" I refer to the set of values that aren't
present along the row, column and within the same 3X3 grid which contains the cell that's referred
to. A rule in Sudoku puzzle game says that the there shouldn't be any repetition of numbers along
each row, column and the subdivided 3X3 grids. This is same as saying that each row and column
and the 3X3 sub-grid should contain all the values from one to nine. The possibilities in each cell
can be computed by checking the row, column and the 3X3 sub-grid and eliminating the ones that
are found. This leaves us with values that aren't entered yet, and which become valid possibilities
for the cell.

PROJECT DESCRIPTION:

Sudoku is a popular logic-based combinatorial number-placement puzzle. The goal is


to fill a 9x9 grid with digits so that each column, each row, and each of the nine 3x3 subgrids
contain all of the digits from 1 to 9. In this project, you'll implement a Sudoku solver using C++.

FEATURES:
5

❖ Input Board: The program should accept a partially filled Sudoku board
as input. You can represent the Sudoku grid as a 2D array or any other
suitable data structure.

❖ Solver Algorithm: Implement an efficient algorithm to solve the Sudoku


puzzle. A common approach is the backtracking algorithm, which
systematically tries each possible value until a solution is found.

❖ Validation: Ensure that the input Sudoku board is valid before attempting
to solve it. Check for duplicate numbers in rows, columns, and 3x3
subgrids.

❖ User Interface: Create a simple user interface to interact with the


program. This can be a command-line interface where users input the
Sudoku puzzle and receive the solved puzzle as output.

❖ Performance Optimization: Optimize your solver algorithm to efficiently


solve Sudoku puzzles of varying difficulty levels. Implement techniques
like constraint propagation or lookahead strategies to improve
performance.

❖ Error Handling: Handle edge cases gracefully, such as invalid input or


unsolvable puzzles. Provide informative error messages to the user when
necessary.

❖ Optional: Generate Puzzles: Extend the program to generate new Sudoku


puzzles of varying difficulty levels. This involves creating a puzzle with
6

a unique solution and removing a certain number of digits to make it


solvable

IMPLEMENTATION STEPS:

❖ Design the data structure to represent the Sudoku board.

❖ Implement input validation to check for duplicates and ensure a valid


Sudoku board.

❖ Develop the backtracking algorithm for solving Sudoku puzzles


recursively.

❖ Create a user interface for inputting Sudoku puzzles and displaying the
solved puzzle.

❖ Test the program with different Sudoku puzzles to ensure correctness


and efficiency.

❖ Handle edge cases and errors to provide a robust user experience

❖ .If desired, implement puzzle generation functionality as an extension.

ALGORITHM:

1. Start.

2. Declare a matrix of N*N size where N=9.

3. First, enter the values of the sudoku and enter 0 for the unassigned cells.
7

4. Print the matrix first before solving.

5. Declare a user-defined function of boolean type.

6. If the 8th row and 9th column (0 indexed matrices) are reached, then return true to avoid
backtracking.

7. If the column value becomes 9, move to the next row and column, and now start from 0.

8. Return false, if the same number is found in a similar column.

9. If the current position contains a value >0, then iterate for the next column.

10. Use a for loop to enter the values in the assigned cells.

11. Call another user-defined function to check whether the entered number is valid or not.

12. Assume a number for a certain position in the matrix.

13. If the assumed number and position are correct, then return true.

14. If the assumption is wrong, then remove the assigned number and proceed with a
different value for the next assumption.

15. Else return false.

16. Display the result according to the boolean value received.

17. If true, then print the solved sudoku puzzle.

18. Else print that no solution exists.

19. Stop.

//C++ Program to Solve Sudoku Problem

#include <iostream>

using namespace std;

#define N 9 // N is the size of the matrix i.e., N*N


8

//Function to print the matrix

void print(int arr[N][N])

for (int i = 0; i < N; i++)

for (int j = 0; j < N; j++)

cout << arr[i][j] << " ";

cout << endl;

//Checks whether it will be legal to assign number to the given row, col

bool isValid(int puzzle[N][N], int row, int col, int number)

//Check if we find the same number in the similar row , we return false

for (int x = 0; x <= 8; x++)

if (puzzle[row][x] == number)

return false;

//Check if we find the same number in the similar column, we return false

for (int x = 0; x <= 8; x++)

if (puzzle[x][col] == number)

return false;

/*Check if we find the same number in


9

the particular 3*3 matrix,

we return false*/

int sRow = row - row % 3,

sCol = col - col % 3;

for (int i = 0; i < 3; i++)

for (int j = 0; j < 3; j++)

if (puzzle[i + sRow][j +

sCol] == number)

return false;

return true;

//Function to Solve the sudoku puzzle

bool solution(int puzzle[N][N], int row, int col)

/* If the 8th row and 9th column (0 indexed matrix) is reached,

then return true to avoid backtracking*/

if (row == N - 1 && col == N)

return true;

/*If column value becomes 9, move to next row and column

Now start from 0*/

if (col == N) {

row++;
10

col = 0;

/If the current position contains value >0, then iterate for next column/

if (puzzle[row][col] > 0)

return solution(puzzle, row, col + 1);

for (int number = 1; number <= N; number++)

//Check whether a number (1-9) can be placed in the given row,col

if (isValid(puzzle, row, col, number))

/* Let the number is present in the current(row,col)

position of the puzzle and let the assigned

number in that position is correct*/

puzzle[row][col] = number;

// Checking for next possibility with next column

if (solution(puzzle, row, col + 1))

return true;

/* If assumption is wrong, then remove the assigned number

Proceed with a different value for next assumption*/

puzzle[row][col] = 0;

}
11

return false;

// Driver Code

int main()

// Here 0 means unassigned cells

int puzzle[N][N] = { { 0, 7, 0, 0, 0, 0, 0, 0, 9 },

{ 5, 1, 0, 4, 2, 0, 6, 0, 0 },

{ 0, 8, 0, 3, 0, 0, 7, 0, 0 },

{ 0, 0, 8, 0, 0, 1, 3, 7, 0 },

{ 0, 2, 3, 0, 8, 0, 0, 4, 0 },

{ 4, 0, 0, 9, 0, 0, 1, 0, 0 },

{ 9, 6, 2, 8, 0, 0, 0, 3, 0 },

{ 0, 0, 0, 0, 1, 0, 4, 0, 0 },

{ 7, 0, 0, 2, 0, 3, 0, 9, 6 } };

cout << "Before Solving " << endl;

print(puzzle);

cout << "" << endl;

cout << "After Solving " << endl;

if (solution(puzzle, 0, 0))

print(puzzle);

else
12

cout << "No solution exists " << endl;

return 0;

Before Solving

070000009

510420600

080300700

008001370

023080040

400900100

962800030

000010400

700203096

After Solving

374168259

519427683

286395714

698541372

123786945
13

457932168

962874531

835619427

741253896

Sudoku is a popular logic-based number placement puzzle. You can implement


Sudoku in C++ using various approaches, but typically you'll need to create data structures to
represent the Sudoku grid, implement functions to check whether a number is valid in a certain
position, and use backtracking or other algorithms to solve the puzzle.

Here's a high-level overview of how you might approach it:

1. *Data Structures*: You'll need a data structure to represent the Sudoku grid. A 2D array or a
vector of vectors is a common choice.

2. *Input/Output*: Implement functions to input a Sudoku puzzle from the user or from a file, and
to output the solved puzzle.

3. *Validation*: Write functions to check whether a number can be placed in a certain position
according to the Sudoku rules (no duplicate numbers in the same row, column, or 3x3 subgrid).

4. *Backtracking Algorithm*: Use a backtracking algorithm to solve the Sudoku puzzle. The
algorithm tries different numbers in empty cells, and if it reaches a dead end, it backtracks and
tries a different number.

5. *Main Loop*: Your main function should orchestrate the process, taking input, solving the
puzzle, and providing output.
14

MODULES:

Here's a simple example of how you can start implementing a Sudoku solver in C++

:#include <iostream>

#include <vector>

using namespace std;

const int N = 9;

bool isSafe(vector<vector<int>>& board, int row, int col, int num) {

for (int x = 0; x < N; ++x)

if (board[row][x] == num || board[x][col] == num)

return false

int startRow = row - row % 3;

int startCol = col - col % 3


15

for (int i = 0; i < 3; ++i)

for (int j = 0; j < 3; ++j)

if (board[i + startRow][j + startCol] == num)

return false;

return true;

bool solveSudoku(vector<vector<int>>& board) {

int row, col;

bool isEmpty = true

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

for (col = 0; col < N; ++col) {

if (board[row][col] == 0) {

isEmpty = false;

break;

if (!isEmpty) break;

if (isEmpty) return trun

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

if (isSafe(board, row, col, num)) {

board[row][col] = num;
16

if (solveSudoku(board))

return true;

board[row][col] = 0;

return false;

void printBoard(vector<vector<int>>& board) {

for (int i = 0; i < N; ++i) {

for (int j = 0; j < N; ++j) {

cout << board[i][j] << " ";

cout << endl;

int main() {

vector<vector<int>> board = {

{5, 3, 0, 0, 7, 0, 0, 0, 0},

{6, 0, 0, 1, 9, 5, 0, 0, 0},

{0, 9, 8, 0, 0, 0, 0, 6, 0},

{8, 0, 0, 0, 6, 0, 0, 0, 3},

{4, 0, 0, 8, 0, 3, 0, 0, 1},

{7, 0, 0, 0, 2, 0, 0, 0, 6},
17

{0, 6, 0, 0, 0, 0, 2, 8, 0},

{0, 0, 0, 4, 1, 9, 0, 0, 5},

{0, 0, 0, 0, 8, 0, 0, 7, 9}

};

if (solveSudoku(board))

printBoard(board);

else

cout << "No solution exists." << endl;

return 0;

}
18

CONCLUSION:

In conclusion, implementing Sudoku in C++ has proven to be a challenging yet


rewarding endeavor. Through the use of backtracking algorithms such as recursion, we've been
able to efficiently solve Sudoku puzzles of varying difficulties. By breaking down the problem
into smaller, manageable steps, we've created a robust solution that can handle even the most
complex Sudoku grids. Additionally, employing object-oriented principles has allowed for
modular and scalable code, facilitating easy maintenance and extension. Overall, this project has
not only enhanced our understanding of C++ programming techniques but also showcased the
power of algorithmic thinking in solving real-world puzzles.

REFERENCE:

❖ https://codereview.stackexchange.com/questions/37430/sudoku-solver-in-c

❖ https://www.geeksforgeeks.org/sudoku-backtracking-7/amp/

❖ https://copyassignment.com/sudoku-game-in-cpp/

❖ https://www.studytonight.com/post/solve-sudoku-puzzle-in-c-java
19

❖ https://stackoverflow.com/questions/19022739/sudoku-solver-in-c

You might also like