BCA 6th Sem Project
BCA 6th Sem Project
A Project Report On
Sudoku Generator and Solver using Back-tracking Algorithm
Submitted to
Department of Computer Application
National College of Computer Studies
Submitted By:
Rameshwor Shrestha
Salin Manandhar
October 2024
Tribhuwan University
Supervisor’s Recommendation
I hereby recommend that this project prepared under my supervision by Rameshwor
Shrestha and Salin Manandhar entitled “Sudoku Generator and Solver using
Backtracking Algorithm" in partial fulfillment of the requirements for the degree of
Bachelor of Computer Application is recommended for the final evaluation.
………………………………………..
SIGNATURE
Yuba Raj Devkota
SUPERVISOR
Faculty Member
Department of Computer Application National
College of Computer Studies
i
i
Tribhuwan University
Faculty of Humanities and Social Sciences
National College of Computer Studies
LETTER OF APPROVAL
This is to certify that this project prepared by Rameshwor Shrestha and Salin Manandhar
entitled “Sudoku Generator and Solver using Backtracking Algorithm " in partial
fulfillment of the requirements for the degree of Bachelor in Computer Application has
been evaluated. In our opinion it is satisfactory in the scope and quality as a project for
the required degree.
Signature of Supervisor Signature of HOD/ Coordinator
iii
ABSTRACT
This project presents the development of a comprehensive Sudoku Solver and Generator
application utilizing the Backtracking algorithm. The system offers two primary
functionalities: solving Sudoku puzzles and generating new ones at varying levels of
difficulty, including easy, medium, hard, and expert. The Backtracking algorithm ensures
an efficient and accurate solution to any valid Sudoku puzzle, guaranteeing consistency
and correctness in puzzle-solving. The application also integrates user authentication with
secure login and registration features, allowing users to create accounts, track their
progress, and securely save their game data. A dynamic leaderboard feature ranks players
based on performance metrics such as puzzle-solving time, difficulty level, and overall
scores, fostering a competitive environment. The project is designed with an interactive
and user-friendly interface, utilizing Java Swing for a visually appealing and accessible
experience for both casual players and Sudoku enthusiasts. Emphasizing security and user
engagement, the project incorporates robust authentication protocols and real-time
leaderboard updates, aiming to deliver an engaging, competitive, and educational
experience for users. This Sudoku Solver and Generator serves as both a learning tool and
a platform for enhancing logical thinking and problem-solving skills.
i
v
ACKNOWLEDGEMENT
We would like to extend our heartfelt gratitude to our supervisor, Mr. Yuba Raj Devkota,
for his invaluable guidance, continuous monitoring, and unwavering motivation
throughout all phases of this project. His expertise, constructive feedback, and insightful
suggestions were instrumental in shaping the direction and success of this endeavor. We
deeply appreciate his patience, support, and the inspiration he provided, which helped us
overcome various challenges and achieve our goals. We also wish to express our sincere
appreciation to all other supervisors, professors, and mentors who offered their time,
knowledge, and encouragement. Their collective support and advice were crucial in
refining our approach and enhancing the quality of our work. Additionally, we are
grateful to our friends, peers, and family members for their constant encouragement,
moral support, and willingness to assist whenever needed. This project would not have
been possible without the collaborative efforts and contributions of everyone involved,
and we are truly thankful for their role in making it a success.
Rameshwor Shrestha
Salin Manandhar
Table of Content
ABSTRACT.......................................................................................................................iv
v
ACKNOWLEDGEMENT...................................................................................................v
Table of Content.................................................................................................................vi
List Of Abbreviation........................................................................................................viii
List of Figures....................................................................................................................ix
List of Tables.......................................................................................................................x
Chapter 1: Introduction.......................................................................................................1
1.1 Introduction...............................................................................................................1
1.3 Objectives..................................................................................................................2
v
i
3.2.2 Component Diagram........................................................................................20
4.1 Implementation........................................................................................................24
4.2 Testing.....................................................................................................................33
5.1 Conclusion...............................................................................................................43
List Of Abbreviation
ID Identification
UI User Interface
MySQL My Structured Query Language
SDLC System Development Life Cycle
SQL Structured Query Language
vi
i
List of Figures
Figure 3.1: Waterfall Model.................................................................................................
9
Figure 3.2: Usecase Diagram of Sudoku Generator and Solver ........................................
11
Figure 3.3: Object Diagram of Sudoku Generator and Solver...........................................
13
Figure 3.4: Class Diagram of Sudoku Generator and Solver.............................................
14
Figure 3.5: State Diagram of Sudoku Generator and Solver .............................................
15
Figure 3.6: Sequence Diagram of Sudoku Generator and Solver ......................................
16
Figure 3.7: Activity Diagram of Sudoku Generator and Solver ........................................
17
v
iii
Figure 3.8: Refinement Class diagram of Sudoku Generator and Solver ..........................
18
Figure 3.9: Refinement Object Diagram of Sudoku Generator and Solver .......................
19
Figure 3.10: Component Diagram of Sudoku Generator and Solver.................................
20
Figure 3.11: Deployment Diagram of Sudoku Generator and Solver ...............................
21
Figure 4.1: Leaderboard MySQL Table of the Sudoku Generator and Solver ..................
25
Figure 4.2: User MySQL Table of the Sudoku Generator and Solver...............................
25
Figure 4.3: Main Menu of Sudoku Generator and Solver .................................................
25
Figure 4.4: Login of Sudoku Generator and Solver...........................................................
26
Figure 4.5: Registration of Sudoku Generator and Solver.................................................
26
Figure 4.6: Sudoku Player of Sudoku Generator and Solver .............................................
27
Figure 4.7: Sudoku Solver of Sudoku Generator and Solver.............................................
27
Figure 4.8: Leaderboard of Sudoku Generator and Solver ................................................
28
Figure 4.9: First Code of SudokuSolver class in Sudoku Game........................................
28
Figure 4.10: Second Code of SudokuSolver class in Sudoku Game .................................
29
Figure 4.11: First Code of SudokuGenerator class in Sudoku Game ................................
30
Figure 4.12: Second Code of SudokuGenerator class in Sudoku Game............................
31
ix
List of Tables
Table 4.1: Unit Testing of Registration in Sudoku Generator and Solver .........................
34
Table 4.2: Unit Testing of Login in Sudoku Generator and Solver ...................................
35
Table 4.3: Unit Testing of ability to play game in Sudoku Generator and Solver ............
36
Table 4.4: Unit Testing of Leaderboard in Sudoku Generator and Solver ........................
37
Table 4.5: System Testing for the Sudoku Generator and Solver (User Side) ..................
38
Table 4.6: System Testing for the Sudoku Generator and Solver (Admin Side)...............
42
x
Chapter 1: Introduction
1.1 Introduction
Sudoku is a popular logic-based puzzle that challenges players to fill a 9x9 grid with
numbers in such a way that every row, column, and 3x3 sub-grid contains all digits from 1
to 9 without repetition. Solving Sudoku requires careful analysis, logic, and sometimes
trial-and-error. A Sudoku generator is a tool that creates new puzzles at varying levels of
difficulty, while a solver algorithm automates the process of finding solutions to any valid
Sudoku grid.
The Sudoku Solver in this project utilizes the Backtracking algorithm, a recursive
approach that systematically fills the grid by testing possible values and backtracking
whenever an invalid configuration is encountered. This method ensures that the solution, if
one exists, is reached efficiently without skipping any potential possibilities. The solver
can handle puzzles of any difficulty, from easy to expert-level grids, ensuring that each
puzzle is solved correctly.
On the other hand, the Sudoku Generator employs a random number placement strategy
combined with the Backtracking algorithm to create puzzles. The generator ensures that
each puzzle has a unique solution, adhering to Sudoku’s core rule. Additionally, by
removing a varying number of cells from a fully completed grid, the generator creates
puzzles of different difficulty levels, providing users with a range of challenges.
The project also includes user-focused features like Login/Registration and a Leaderboard.
These features allow users to create accounts, track their progress, and compare their
performance with others. The leaderboard ranks players based on the time they take to
solve puzzles and the difficulty level of the puzzles they complete, adding a competitive
aspect to the experience.
As a whole, the Sudoku Generator and Solver project not only provides an efficient
algorithmic approach to generating and solving puzzles but also enhances the user
experience by incorporating features like authentication and real-time competitive ranking.
This combination of functionality makes the project both technically robust and engaging
for Sudoku enthusiasts.
1
1.2 Problem Statement
Existing Sudoku applications often lack essential features or fail to provide a user-friendly
interface, making it difficult for users to enjoy a smooth puzzle-solving experience.
Common issues include limited puzzle variety, confusing navigation, and the absence of
personalized options, leaving users seeking a better solution.
This project aims to develop a comprehensive Sudoku application that blends advanced
functionality with ease of use and a visually appealing design. By focusing on a
usercentered interface, the app will allow users to easily generate, solve, and explore
Sudoku puzzles without hassle.
Additionally, the app will introduce unique features such as adjustable puzzle difficulty
and a leaderboard to foster competition among players. Emphasizing both performance
and aesthetics, this Sudoku application is designed to meet the evolving needs of puzzle
enthusiasts, setting a new benchmark in puzzle games.
1.3 Objectives
The objectives of this project are:
• To design a Sudoku using Java.
• To implement Backtracking Algorithm for Generating and Solving.
However, the application will not include online cloud saving, which limits social
interaction and data persistence. Furthermore, the app may lack comprehensive tutorials or
in-depth user support resources for new players.
2
1.6 Report Organization
Chapter 1: Introduction
Chapter one introduces the concept of this project. It describes the problems that has been
existing and how its objective can tackle it. It also presents the scope and limitations of the
project.
This chapter focuses on the basic ideology of how this project will be build. It traces out
the study of different platforms and their workings.
This chapter describes the requirements gathering, feasibility study, and designing of the
project. It includes diagrams, functionality analysis, requirement gathering technique and
process model.
This chapter is designed to give information about how the project has been implemented,
what kind of software and tools has been used and the type of testing that the project has
gone through.
This chapter includes the possible outcome of this project, conclusion and future
recommendations.
3
Puzzle Difficulty Levels: Sudoku puzzles can be categorized into different difficulty
levels—easy, medium, hard, and expert—based on the number of given clues (pre-filled
cells) and the complexity of the solving process. Easy puzzles provide more clues and
require simpler logical techniques, whereas harder puzzles provide fewer clues and require
more advanced solving strategies, like naked pairs or x-wing.
Solution Uniqueness: A well-designed Sudoku puzzle has only one valid solution.
Ensuring uniqueness is critical for the integrity of the puzzle. A generator must check that
after placing a certain number of clues, the puzzle still maintains a unique solution. This is
usually done by applying solving algorithms to validate that no alternative solutions exist.
Sudoku Solvers: These applications focus primarily on solving existing Sudoku puzzles.
Users can input a partially filled grid, and the solver employs algorithms, such as
Backtracking or Constraint Satisfaction, to find the solution. Some solvers provide
additional features, like step-by-step solving processes, highlighting mistakes, and offering
insights into solving techniques. Examples include "Sudoku Solver Pro" and "Sudoku
Assistant."
4
Sudoku Generators: These apps specialize in creating new Sudoku puzzles for users to
solve. They offer varying levels of difficulty and often include features to ensure unique
solutions. Generators typically allow users to select the desired difficulty level, and some
provide customization options, such as grid size and formatting. Popular examples include
"Sudoku Generator" and "247Sudoku."
Hybrid Applications: Many modern Sudoku apps combine both solving and generating
functionalities, providing users with a comprehensive experience. These applications
allow users to create their own puzzles or solve those generated by the app. Additionally,
hybrid apps often include features like hint systems, user accounts for tracking progress,
and social features such as leaderboards. Examples include "Microsoft Sudoku" and
"Sudoku.com."
Moreover, there are also specialized apps that focus on specific variations of Sudoku, such
as "Killer Sudoku," "Samurai Sudoku," and "Sudoku with irregular regions." These
variants add complexity and challenge to the traditional format, appealing to experienced
players seeking new experiences.
In the context of Sudoku, the process begins by identifying an empty cell in the 9x9 grid.
The algorithm then attempts to place numbers from 1 to 9 into that cell. For each number,
the algorithm performs a validity check to ensure that placing the number does not violate
any of Sudoku's fundamental rules: no number may appear more than once in any row,
column, or 3x3 sub-grid [2]. This checking mechanism is crucial, as it prevents invalid
configurations early in the process.
When a valid number is placed, the algorithm proceeds recursively to the next empty cell.
This step-by-step approach continues until the grid is completely filled. If the algorithm
encounters a situation where no valid numbers can be placed in a subsequent empty cell, it
5
backtracks to the previous cell where a number was placed, removes that number, and tries
the next possible number [3]. This process of going back to the last valid configuration
allows the algorithm to explore different potential solutions efficiently.
Backtracking is particularly effective for Sudoku due to the structured nature of the puzzle.
Each placement has direct implications on the remaining empty cells, and the constraints
inherent in Sudoku make it possible to eliminate many invalid configurations quickly [2].
This systematic exploration of possibilities is where Backtracking shines; although it may
initially appear inefficient, its pruning mechanism significantly enhances performance.
Backtracking can also be applied to generate Sudoku puzzles. In this context, the
algorithm starts with a fully filled grid and then systematically removes numbers while
ensuring that the resulting puzzle retains a unique solution. This dual capability—solving
and generating—makes Backtracking a versatile choice for Sudoku applications.
Kovacs outlines a few brute force strategies for resolving Sudoku problems. The
"unconstrained grid" puzzle has a solution that is generated at random by the simplest
approach, and then the program verifies that the solution is correct. If not, the steps are
carried out again until a solution is discovered [5]. This algorithm is easy to use and,
because it considers every potential answer, will provide a workable solution for any issue.
Though Kovacs claims the algorithm can be optimized, this approach can be
timeconsuming.
In general, the brute force method scans the blank squares, adding numbers from the
available options or eliminating unsuccessful selections in the event that a "dead-end" is
encountered [5]. Brute force, for instance, solves a puzzle by placing the number "1" in the
first square. The software advances to the next square and inserts the number "1" there if
the digit is permitted to be there by checking the row, column, and box. When the software
determines that the number "1" is incorrect, it advances the digit by one, making it 2. The
program reverts to the previous square when it detects a square where none of the digits (1
6
to 9) are allowed. That square's value rises by one. Until all 81 squares are filled with the
correct digits, the process is repeated.
While Backtracking is the primary algorithm for this project, several other algorithms are
also there for Sudoku application:
Dancing Links: This algorithm, developed by Donald Knuth, is an efficient method for
solving exact cover problems, which include Sudoku. Dancing Links uses a data structure
to represent the puzzle as a matrix, allowing for quick updates as numbers are placed or
removed [6]. This method is particularly effective for finding all possible solutions to a
Sudoku puzzle rather than just one.
Constraint Satisfaction: This approach focuses on defining constraints for each cell and
uses techniques to propagate these constraints to narrow down possibilities. Algorithms in
this category often employ techniques such as Arc Consistency, which helps eliminate
impossible values from cells based on the constraints of neighbouring cells [7]. While
powerful, this method can be more complex to implement compared to Backtracking.
In conclusion, the Backtracking algorithm remains the most suitable choice for generating
and solving Sudoku puzzles due to its efficiency and simplicity. While other algorithms,
such as Dancing Links and Constraint Satisfaction, offer alternative approaches with
specific advantages, Backtracking's ability to effectively prune invalid paths makes it the
optimal choice for this project. Understanding these various algorithms provides a
foundation for developing a robust and efficient Sudoku application that meets user needs.
7
8
Chapter 3: System Analysis and Design
3.1 System Analysis
This project follows the Waterfall model throughout the Software Development Life Cycle
(SDLC). The choice of the Waterfall model is based on its effectiveness in rapidly
building a foundational system within a limited timeframe. It provides a clear, sequential
structure that helps define timelines and set specific deadlines for each phase of
development.
The model's linear approach is particularly suitable for this project, as the requirements
were well-defined from the start. This allowed for a smooth flow through the
development stages - requirements gathering, system design, implementation, testing,
deployment, and maintenance - ensuring efficient project management and execution.
9
3.1.1 Requirement Analysis
The process of obtaining important specifications that will be utilized to create a system is
known as requirement identification [9]. There are several ways to obtain requirements,
such as reviewing the existing system, conducting interviews, using questionnaires, etc.
i. Functional Requirement
The Sudoku application will encompass a range of features designed to enhance the
puzzlesolving experience for users. It will allow users to generate and solve Sudoku
puzzles of varying difficulty levels, utilizing a robust Backtracking algorithm to ensure
efficient and accurate solutions. Users can select different difficulty settings, ranging from
easy to expert, making the application suitable for both beginners and experienced players.
To personalize the experience, the application will include user account functionalities,
allowing users to register and log in securely. This will enable them to save their
progress, track their performance over time, and access their preferred settings from any
device. The interface will be intuitive and user-friendly, providing clear navigation
between puzzle generation, solving, and user account management.
The design will prioritize ease of use, with visual feedback for user actions and essential
information displayed clearly, such as the current puzzle state, hints, and solving
techniques. Navigation will be seamless, enabling users to quickly switch between
generating new puzzles, solving existing ones, and viewing leaderboard rankings.
10
Figure 3.2: Usecase Diagram of Sudoku Generator and Solver
The application allows users to register and log in, creating personalized accounts for
tracking their progress. After logging in, users are taken to the main menu, where they can
choose between two primary features: Generate Sudoku and Solve Sudoku.
In the Generate Sudoku section, users can play a Sudoku game by generating new puzzles
of varying difficulty levels. This provides an interactive experience for players of all skill
levels.
In the Solve Sudoku section, users have the ability to load previously saved puzzles, save
their current progress, and display the solution to any puzzle they are working on. This
functionality offers flexibility for users to solve puzzles at their own pace.
Additionally, the app features a Leaderboard, where users can view their rankings based
on factors such as solving time and puzzle difficulty, adding a competitive element to the
experience.
11
The application is compatible with a wide range of Java desktop environments, ensuring
optimal performance across various operating systems. It supports multiple screen sizes
and resolutions, providing an excellent user experience regardless of the display used.
Security measures are in place to protect access to Sudoku files and prevent unauthorized
modifications, ensuring safe handling of user data and preferences.
Designed with usability in mind, the application offers ease of learning and navigation for
users of all skill levels. Its interface is intuitive, allowing both beginners and experienced
players to engage with the puzzles effortlessly. Reliability has been prioritized, resulting in
stable performance with minimal crashes and bugs, supported by robust error handling and
recovery mechanisms.
i. Technical
This system meets the technical feasibility criteria by leveraging existing technologies
such as Java, which is widely supported and has extensive documentation and community
resources. Java is a robust programming language that provides a solid foundation for
desktop application development, ensuring reliability and performance. The application
will utilize Java's rich libraries and frameworks to facilitate user interface design and
puzzle-solving functionality.
Additionally, the system incorporates local file management for storing user preferences
and puzzle data, ensuring seamless access and synchronization across sessions. Security
measures will be implemented to safeguard user data and preferences, enhancing overall
system integrity. This combination of technologies and methodologies ensures a stable and
efficient Sudoku application that meets user needs effectively.
ii. Operational
The application features an intuitive and user-friendly interface, designed to make it easy
for users to navigate and engage with their Sudoku puzzles with minimal effort. The
layout prioritizes user experience, ensuring that all essential features are readily accessible.
12
The main screen presents a visually appealing design that highlights the current puzzle
along with crucial information such as difficulty level and the number of empty cells
remaining.
Key controls, such as options for generating new puzzles, saving progress, and accessing
the leaderboard, are prominently positioned for quick access. The interface includes visual
feedback for user actions, enhancing interactivity and engagement. Overall, the design
aims to provide a seamless and enjoyable puzzle-solving experience for users of all skill
levels.
iii. Economic
The system will be economically feasible, as the primary resources required for
development and operation are a laptop, an internet connection, and electricity. This low
barrier to entry makes it accessible for both individual developers and small teams,
allowing for a cost-effective approach to building and maintaining the music player
application.
The object diagram illustrates the connections between the major parts of the Sudoku
13
Solver application, outlining its organizational structure. The App class controls the
Sudoku panel (sudokuFramePanel), the main window (mainFrame), and the username of
the user.
While the Registration class facilitates the registration of new users, the LoginRegistration
class manages user login.
The MainMenu class allows users to see the leaderboard and play Sudoku games after
logging in. Scores are shown in the Leaderboard panel, sorted by difficulty.
The board, the current state of the game, and references to the SudokuGenerator and
SudokuSolver for puzzle creation and solution are all managed by the PlaySudoku class.
14
The main components and their connections inside the Sudoku Solver application are
depicted in this class diagram. Panel navigation, user sessions, and the main interface are
all controlled by the App class. User authentication and account creation are handled by
the LoginRegistration and Registration classes. The MainMenu allows users to navigate to
the game or leaderboard, while the Leaderboard interacts with the SudokuDatabase to save
and retrieve data while displaying scores dependent on difficulty.
The board, score, and lives are all managed by the PlaySudoku class. It collaborates with
the SudokuSolver to solve puzzles and the SudokuGenerator to create new ones. All of
these parts work together to control gameplay, user sessions, and scorekeeping.
This state diagram represents the flow of the user experience in the Sudoku Solver
application. It begins in the Idle state, where users can either start the login or registration
15
process. Upon successful login or registration, the system transitions to the Game Setup
state, where a puzzle is generated.
From there, users enter the Playing state, where they interact with the puzzle. The game
periodically moves to the Validation state to check the puzzle's correctness. If the puzzle is
invalid or completed, the game transitions to Game Over. Users can restart the game or
choose to log out, ending the session. This diagram shows the main interactions from login
to gameplay and logout.
The sequence diagram shows the interaction between a user and various components of a
Sudoku system, focusing on logging in and solving puzzles.
Initially, the user enters their credentials in the LoginRegistration component, which then
communicates with the JdbcConn (a database connection) to validate the user's
credentials.
If the credentials are valid, the database returns confirmation, and the user is logged in
successfully.
Next, the user requests to generate a Sudoku puzzle. This triggers the SudokuGenerator to
create a puzzle and send it to the SudokuGamePanel for the user to start playing. Once the
user solves the puzzle, the solution is passed to the SudokuSolver, which checks if it is
correct. The solution is then validated by the ValidatePuzzle component, which returns the
16
result of the validation. The user is notified of whether the solution is correct or incorrect
based on this result.
This activity diagram outlines the user flow in a Sudoku game application. Upon starting
the program, the user must log in or register if they are new. Once logged in, the main
menu offers two choices: play Sudoku or view the leaderboard.
If the user opts to play, a puzzle is generated, and they attempt to solve it. The system
checks the solution, updating the leaderboard for correct answers or prompting reattempts
17
for errors. Alternatively, if the user selects "View Leaderboard," the system displays top
scores. After either action, the user completes their activity and the process ends.
The main components of a Sudoku application are divided into multiple classes in this
class diagram. The App class acts as the entrance point, controlling the user interface and
panel navigation, including SudokuFrame and Login. While the MainMenu offers options
to launch new games or check leaderboards, the Login/Registration class manages user
authentication, including username and password validation. The interface of the Sudoku
board is rendered by SudokuFrame. Through interactions with the SudokuDatabase, which
uses JDBC connections to store and retrieve player data, Leaderboard controls how the top
scores are displayed. Different difficulty levels are supported, and problems with
legitimate solutions are guaranteed by the SudokuGenerator and SudokuSolver classes,
18
which also handle puzzle creation and validation. Last but not least, PlaySudoku manages
player input and game mechanics while the game is being played.
This object diagram depicts the runtime structure of a Sudoku application, showing
specific instances and their interconnections. The app: App object is the central
component, storing the user's username and linking to the main Sudoku frame. The
loginPanel: LoginRegistration manages user authentication, referencing the main
application and its associated frame. The mainMenuPanel: MainMenu provides navigation
options and stores the user's name. The leaderboardPanel: Leaderboard object manages the
display of high scores using a combo box for difficulty selection and a table model for
leaderboard entries, interacting with the database: SudokuDatabase for data retrieval. The
sudokuFramePanel: SudokuFrame renders the Sudoku board and menu interface.
Additionally, the playSudokuPanel: PlaySudoku manages game logic, tracking user
progress, score, and time. Other objects, such as generator: SudokuGenerator and solver:
SudokuSolver, handle puzzle creation and validation, ensuring the game runs smoothly.
The connection:
JdbcConn manages the database connection for storing and retrieving user data.
19
3.2.2 Component Diagram
This component diagram shows the structure and interaction of modules in a Sudoku game
system. The User Interface (UI) includes components like the Main Menu for choosing
between gameplay or viewing the leaderboard, the Play Sudoku UI for gameplay, and the
Login/Registration UI for user authentication.
20
The Game Logic consists of the Sudoku Generator for creating puzzles, the Solver for
solving them, and the Validator for checking solutions. The Registration Logic handles
user registration, while the Database, managed by JdbcConn, stores user and puzzle data,
supporting the game's functionality. These components work together to manage users,
generate puzzles, and validate solutions.
The deployment diagram shows the architecture of the Sudoku Solver application, where
users interact by registering, logging in, or accessing the game menu. On the client side,
key components include the MainMenu for navigation, PlaySudoku for gameplay, and the
Leaderboard for displaying top scores, all interacting with the Sudoku Database for storing
scores.
21
separation between gameplay and user data management for efficient and organized
processing.
Decision Tree: The algorithm can be visualized as a decision tree, where each node
represents a state of the Sudoku grid. The root node represents the initial empty grid, and
each child node corresponds to a valid placement of a number in one of the empty cells.
The depth of the tree is equal to the number of empty cells, and the leaves represent
complete configurations of the grid. Backtracking systematically traverses this tree,
exploring paths until it either finds a solution or exhausts all possibilities.
The algorithm employs these constraints to prune the search space, allowing it to discard
invalid paths early in the process.
Given a 9×9 Sudoku grid 𝑃 where some cells are pre-filled with numbers (from 1 to 9)
and others are empty (denoted as 0), the goal is to fill in all the empty cells such that each
row, each column, and each 3×3 sub-grid contains all the numbers from 1 to 9 without
repetition. Variables and Functions
Puzzle Grid: 𝑃 is a 9×9 grid where 𝑃[𝑖][𝑗] represents the value at row 𝑖 and column 𝑗.
Row and Column: The algorithm iterates over the grid using row and col indices.
22
The backtracking algorithm can be expressed mathematically as follows:
Base Case:
𝑠𝑜𝑙𝑣𝑒(𝑃, 𝑖,𝑗)
𝑇𝑟𝑢𝑒, 𝑖𝑓 𝑖 (𝐴𝑙𝑙 𝑟𝑜𝑤𝑠 𝑎𝑣𝑒 𝑏𝑒𝑒𝑛 𝑓𝑖𝑙𝑙𝑒𝑑, 𝑝𝑢𝑧𝑧𝑙𝑒 𝑖𝑠
𝑠𝑜𝑙𝑣𝑒𝑑)
= {𝑠𝑜𝑙𝑣𝑒(𝑃,𝑖 + 1,0), 𝑖𝑓 𝑗 (𝐸𝑛𝑑 𝑜𝑓 𝑡 𝑒 𝑐𝑢𝑟𝑟𝑒𝑛𝑡 𝑟𝑜𝑤, 𝑚𝑜𝑣𝑒 𝑡𝑜
𝑛𝑒𝑥𝑡 𝑟𝑜𝑤) 𝑠𝑜𝑙𝑣𝑒(𝑃,𝑖, 𝑗 + 1), 𝑖𝑓 𝑃 (𝐶𝑢𝑟𝑟𝑒𝑛𝑡 𝑐𝑒𝑙𝑙
𝑓𝑖𝑙𝑙𝑒𝑑, 𝑚𝑜𝑣𝑒 𝑡𝑜 𝑛𝑒𝑥𝑡 𝑐𝑒𝑙𝑙)
Recursive Step:
Validation Function: The isValid function ensures that placing a value 𝑣 at 𝑃[𝑖][𝑗] is
consistent with Sudoku rules:
𝑖𝑠𝑉𝑎𝑙𝑖𝑑(𝑃,𝑖, 𝑗, 𝑣)
𝐹𝑎𝑙𝑠𝑒,𝑖𝑓 𝑃[𝑖][𝑘] = 𝑣 𝑜𝑟 𝑃[𝑘][𝑗] = 𝑣 𝑓𝑜𝑟 𝑎𝑛𝑦 𝑘
= {𝐹𝑎𝑙𝑠𝑒, 𝑖𝑓 𝑃[𝑚][𝑛] = 𝑣 𝑓𝑜𝑟 𝑎𝑛𝑦 (𝑚, 𝑛) 𝑖𝑛 3× 3 𝑠𝑢𝑏 𝑔𝑟𝑖𝑑
𝑐𝑜𝑛𝑡𝑎𝑖𝑛𝑖𝑛𝑔 (𝑖,𝑗)
𝑇𝑟𝑢𝑒, 𝑖𝑓 𝑣 𝑖𝑠 𝑛𝑜𝑡 𝑝𝑟𝑒𝑠𝑒𝑛𝑡 𝑖𝑛 𝑡ℎ𝑒 𝑠𝑎𝑚𝑒 𝑟𝑜𝑤, 𝑐𝑜𝑙𝑢𝑚𝑛, 𝑜𝑟
𝑠𝑢𝑏 𝑔𝑟𝑖𝑑
𝑓𝑎𝑙𝑠𝑒, 𝑖𝑠 𝑠𝑜𝑙𝑣𝑒𝑑
𝑠𝑜𝑙𝑣𝑒(𝑖, 𝑗) = { 𝑖𝑓 𝑛𝑜 𝑣𝑎𝑙𝑖𝑑 𝑛𝑢𝑚𝑏𝑒𝑟 𝑐𝑎𝑛 𝑏𝑒
𝑠𝑜𝑙𝑣𝑒(𝑖, 𝑗 + 1), 𝑝𝑙𝑎𝑐𝑒𝑑 𝑖𝑛 (𝑖,𝑗)
𝑏𝑎𝑐𝑘𝑡𝑟𝑎𝑐𝑘,
𝑖𝑓 𝑛𝑢𝑚𝑏𝑒𝑟 𝑖𝑠 𝑣𝑎𝑙𝑖𝑑 𝑎𝑛𝑑 𝑝𝑙𝑎𝑐𝑒𝑑 𝑖𝑛
(𝑖, 𝑗)
𝑖𝑓 𝑝𝑙𝑎𝑐𝑒𝑚𝑒𝑛𝑡 𝑙𝑒𝑎𝑑𝑠 𝑡𝑜 𝑑𝑒𝑎𝑑𝑒𝑛𝑑
23
Chapter 4: Implementation and Testing
4.1 Implementation
4.1.1 Tools Used
Java
The Sudoku Solver and Generator application was developed using Java, which is
essential since it offers a stable and adaptable framework on which to create the system's
essential features and user interface. Java is mainly utilized in the construction of the
application, and its object-oriented programming features are utilized to organize the code
into readable sections. Java is used to create the Backtracking algorithm, which is the
foundation of the Sudoku Solver and guarantees dependable and effective puzzle solving.
This approach runs smoothly due to Java's robust data structures, including arrays and
recursive functions, which enable the software to handle a range of puzzle complexity
levels.
Java Swing is used for the user interface, which includes buttons, text fields, and graphical
grids that mimic the Sudoku board, to produce an engaging and interactive experience.
This enables users to play Sudoku games that are dynamically generated, submit
problems, and get immediate solutions.
MySQL
The Sudoku Solver and Generator project uses MySQL as its main database management
system to store and handle all of its crucial data. Managing leaderboards, game progress
tracking, user identification, and other essential features all depend heavily on the
database. Users' login credentials are safely saved and verified with the MySQL database
at registration, guaranteeing safe access to their accounts.
24
Furthermore, MySQL is in charge of managing leaderboard data, which includes user
performance measures like solution time, difficulty level, and scores. To provide real-time
rankings, this data is dynamically updated and retrieved, strengthening the application's
competitive feature. Effective data storage, retrieval, and manipulation are made possible
by MySQL's robust querying features, which provide speedy access and reliable
performance. Because MySQL is a dependable option for handling the intricate data
requirements of the Sudoku Solver and Generator application, its use guarantees data
integrity, security, and scalability.
Figure 4.1: Leaderboard MySQL Table of the Sudoku Generator and Solver
Figure 4.2: User MySQL Table of the Sudoku Generator and Solver
i. MainMenu
This class provides the main menu interface of the application, allowing users to navigate
to different sections such as playing Sudoku, solving puzzles, viewing the leaderboard,
and logging out.
25
Figure 4.3: Main Menu of Sudoku Generator and Solver
ii. LoginRegistration
Manages the login and registration screen, providing the user interface for users to sign in
or create new accounts.
26
Figure 4.5: Registration of Sudoku Generator and Solver
iii. PlaySudoku
Provides the user interface for playing Sudoku, including puzzle generation, solving, and
scoring. It allows the user to select the difficulty level, generate a new puzzle, check the
solution, and view the elapsed time and score. It also provides functionality to return to the
main menu.
27
Provides a GUI for interacting with Sudoku puzzles, including functionalities to load and
save puzzles, solve the puzzle, and reset the board. It features a grid-based board for
entering Sudoku numbers.
v. Leaderboard
Provides the interface to display the leaderboard, showing user scores and rankings based
on the difficulty.
28
Figure 4.8: Leaderboard of Sudoku Generator and Solver
SudokuSolver Class
The Backtracking Algorithm is implemented in the SudokuSolver.java. It's implemented in
the private solve method.
29
if (row == 9)
{ return true;
}
}
puzzle[row][col] = 0; // Backtrack
}
}
This loop tries each value from 1 to 9 in the current cell. If a value is valid (doesn't violate
Sudoku rules), it:
• Places the value in the cell
• Recursively tries to solve the rest of the puzzle
• If the recursive call returns true, it means a solution is found
• If not, it backtracks by setting the cell back to 0 and tries the next value
If no value works for this cell, it returns false, which triggers backtracking in the previous
recursive call:
30
return false;
The isValid method (lines 64-82) checks if placing a value in a specific cell violates any
Sudoku rules by checking the row, column, and 3x3 sub-grid.
SudokuGenerator Class
Another part is SudokuGenerator.java which contains an algorithm for generating Sudoku
puzzles.
31
Figure 4.12: Second Code of SudokuGenerator class in Sudoku Game
col) { if (col == 9)
{ col = 0; row++;
if (row == 9) { return
true;
}
}
This part handles moving to the next row when we reach the end of a column. If we've
filled the entire grid (row == 9), we return true as we've found a solution.
if (solution[row][col] != 0) {
return solve(row, col + 1);
}
If the current cell is already filled (not 0), we move to the next cell.
List<Integer> numbers =
generateRandomNumbers(); for (int num :
numbers) {
32
• If the recursive call returns true, we've found a solution.
• If not, we remove the number (backtrack) and try the next number.
return false;
If we've tried all numbers and none work, we return false to trigger backtracking.
The isSafe method (lines 157-159) checks if a number can be placed in a cell without
violating Sudoku rules:
private boolean isSafe(int row, int col, int num) {
return !usedInRow(row, num) && !usedInColumn(col,
num)
&& !usedInBox(row - row % 3, col - col % 3,
num); }
After generating a complete solution, the algorithm removes cells to create the puzzle:
private void removeCells(int
difficulty) { Random rand = new
Random(); int cellsToRemove = 81 -
difficulty; while (cellsToRemove >
0) { int row =
rand.nextInt(9); int col =
rand.nextInt(9);
if (puzzle[row][col] != 0) {
int temp = puzzle[row][col];
puzzle[row][col] = 0; if
(!hasUniqueSolution()) {
puzzle[row][col] = temp;
} else {
cellsToRemove--;
}
}
}
}
33
This method:
• Randomly selects cells to remove.
• Removes a cell's value temporarily.
• Check if the puzzle still has a unique solution.
• If not, it restores the value; if yes, it keeps the cell empty.
• Continues until the desired number of cells are removed.
4.2 Testing
4.2.1 Unit Testing
Requirement no: 1
Status: XXX
Severity: Critical
34
3 Enter the invalid Username =
inputs Null
Password =
Null
Click on Displays dialog As Pass
expected
“Register” “Please fill in all the
Button fields”
Requirement no: 1
Severity: Critical
Summary: Conduct unit testing for the login process within Sudoku Game to ensure its
functionality.
35
1 Open the Displays Login Page As Pass
expected
“Sudoku”
application
2 Enter the invalid Username =
inputs ramu
Password =
ramu123
iii. Unit Testing of the ability to play game in Sudoku Generator and Solver
Requirement no: 1
Module: User Play Sudoku
Status: XXX
Severity: Critical
Values: 1 to 9
Summary: Conduct unit testing for the user to play game within Sudoku Game to ensure
its functionality.
Table 4.3: Unit Testing of ability to play game in Sudoku Generator and Solver
36
Step Steps Inputs Expected result Actual Status
no. result
Module: Leaderboard
Status: XXX
Severity: Critical
Summary: Conduct unit testing for the leaderboard to be shown within Sudoku Game to
ensure its functionality.
37
Step Steps Inputs Expected Actual Status
no. result result
Requirement no: 1
Status: XXX
Severity: Critical
38
Values: Username = “newUser”, Password = “p@ssWord”
Summary: Conduct System testing for Sudoku Game to ensure its functionality
Table 4.5: System Testing for the Sudoku Generator and Solver (User Side)
S.N. Steps Input Expected Result Displayed Remarks
Result
3 Input
invalid Username =
values for rame
registration password =
12345@hell
o confirm
password =
hello@1234
5
Click on As Pass
Displays a dialog
expected
“Register” button
“Registration
Successful”
39
5 Input valid values
for login Username
= newUser
password =
p@ssWord
7 Click on Pass
Displays “Difficulty As
“Generate” button level” dialog box expected
40
11 After completing As Pass
the game Displays a expected
“Congratulations”
dialog box with
score, time taken and
difficulty level
13 Difficulty = All
Selecting the
Difficulty from
drop-down menu
15 Input Digits
Input digits in the
empty fields
41
Empties the field As Pass
Click on “OK” of expected
dialog box and
press “Reset”
“Back”
Requirement no: 1
Status: XXX
Severity: Critical
Summary: Conduct System testing for Sudoku Game to ensure its functionality
Table 4.6: System Testing for the Sudoku Generator and Solver (Admin Side)
42
S.N. Steps Input Expected Result Displayed Remarks
Result
43
maintains a unique solution while varying in difficulty. The solver complements this by
providing a robust mechanism to efficiently solve any valid Sudoku puzzle presented to it,
utilizing similar algorithmic principles.
This project not only showcases the mathematical and logical foundations of Sudoku but
also highlights the significance of problem-solving techniques in programming. Through
this endeavor, we have reinforced our understanding of recursion, backtracking, and
constraint satisfaction problems, which can be applied to various domains beyond Sudoku.
Overall, the implementation serves as an engaging tool for both Sudoku enthusiasts and
developers interested in algorithmic challenges, further inspiring exploration in the field of
artificial intelligence and automated problem-solving.
Notes Feature: Implementing an ability for users to add notes in each cell would provide a
crucial aid for players, especially beginners. This feature would enable users to jot down
possible values for each cell, fostering a deeper engagement with the puzzle-solving
process.
44
45
References
[2] K. L. Eric C. Chi, "Techniques for Solving Sudoku Puzzles," Cornell University,
2012.
[3] "Algorithm to Solve Sudoku | Sudoku Solver," geeksforgeeks, 30 July 2024. [Online].
Available: https://www.geeksforgeeks.org/sudoku-backtracking-7/.
[4] R. K. P. Arnab Kumar Maji, "Sudoku solver using minigrid based backtracking,"
IEEE, 2014.
[8] J. F. Crook, "A Pencil-and-Paper Algorithm for Solving Sudoku Puzzles," Notices of
the AMS, vol. 56, no. 4, p. 460, 2009.
46
Unit Testing for Cab Booking System
1. Unit Testing of Registration
Displays dialog
Enter invalid Username = Null, As
3 "Please fill in all the Pass
registration details Password = Null expected
fields"
47
Status: XXX
Severity: Critical
Values: Username = "JohnDoe", Password = "Pass1234"
Pre-condition: Required one user to log in
48
Time = "12:30 PM" fare details expected
Displays dialog
Enter invalid Credit Card = "", As
2 "Invalid payment Pass
payment details Expiry = "" expected
details"
49
Module: All Modules
Status: XXX
Severity: Critical
Values: Username = "JohnDoe", Password = "Pass1234"
Pre-condition: Required one user to perform all system functionalities
Click on
Opens the As
2 "Register" - Pass
Registration Page expected
button
Username =
Login using Opens homepage As
4 "JohnDoe", Password Pass
valid details with booking options expected
= "Pass1234"
Pick-up = "Main
Displays booking
Book a cab with Street", Destination = As
5 confirmation with Pass
valid details "Airport", Time = expected
fare details
"12:30 PM"
Displays payment
Proceed to Credit Card details As
6 confirmation with Pass
payment provided expected
success message
50