feat: add Sudoku Solver using Backtracking (#7073)

* feat: add Sudoku Solver using Backtracking (issue #6929)

* refactor: remove old Sudoku class from puzzlesandgames package

* Remove old Sudoku implementation and its test class
This commit is contained in:
GOPISETTI NAVADEEP
2025-11-17 14:24:20 +05:30
committed by GitHub
parent cff5d3662e
commit 9f2b675f3e
4 changed files with 210 additions and 207 deletions

View File

@@ -0,0 +1,157 @@
package com.thealgorithms.backtracking;
/**
* Sudoku Solver using Backtracking Algorithm
* Solves a 9x9 Sudoku puzzle by filling empty cells with valid digits (1-9)
*
* @author Navadeep0007
*/
public final class SudokuSolver {
private static final int GRID_SIZE = 9;
private static final int SUBGRID_SIZE = 3;
private static final int EMPTY_CELL = 0;
private SudokuSolver() {
// Utility class, prevent instantiation
}
/**
* Solves the Sudoku puzzle using backtracking
*
* @param board 9x9 Sudoku board with 0 representing empty cells
* @return true if puzzle is solved, false otherwise
*/
public static boolean solveSudoku(int[][] board) {
if (board == null || board.length != GRID_SIZE) {
return false;
}
for (int row = 0; row < GRID_SIZE; row++) {
if (board[row].length != GRID_SIZE) {
return false;
}
}
return solve(board);
}
/**
* Recursive helper method to solve the Sudoku puzzle
*
* @param board the Sudoku board
* @return true if solution is found, false otherwise
*/
private static boolean solve(int[][] board) {
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
if (board[row][col] == EMPTY_CELL) {
for (int number = 1; number <= GRID_SIZE; number++) {
if (isValidPlacement(board, row, col, number)) {
board[row][col] = number;
if (solve(board)) {
return true;
}
// Backtrack
board[row][col] = EMPTY_CELL;
}
}
return false;
}
}
}
return true;
}
/**
* Checks if placing a number at given position is valid
*
* @param board the Sudoku board
* @param row row index
* @param col column index
* @param number number to place (1-9)
* @return true if placement is valid, false otherwise
*/
private static boolean isValidPlacement(int[][] board, int row, int col, int number) {
return !isNumberInRow(board, row, number) && !isNumberInColumn(board, col, number) && !isNumberInSubgrid(board, row, col, number);
}
/**
* Checks if number exists in the given row
*
* @param board the Sudoku board
* @param row row index
* @param number number to check
* @return true if number exists in row, false otherwise
*/
private static boolean isNumberInRow(int[][] board, int row, int number) {
for (int col = 0; col < GRID_SIZE; col++) {
if (board[row][col] == number) {
return true;
}
}
return false;
}
/**
* Checks if number exists in the given column
*
* @param board the Sudoku board
* @param col column index
* @param number number to check
* @return true if number exists in column, false otherwise
*/
private static boolean isNumberInColumn(int[][] board, int col, int number) {
for (int row = 0; row < GRID_SIZE; row++) {
if (board[row][col] == number) {
return true;
}
}
return false;
}
/**
* Checks if number exists in the 3x3 subgrid
*
* @param board the Sudoku board
* @param row row index
* @param col column index
* @param number number to check
* @return true if number exists in subgrid, false otherwise
*/
private static boolean isNumberInSubgrid(int[][] board, int row, int col, int number) {
int subgridRowStart = row - row % SUBGRID_SIZE;
int subgridColStart = col - col % SUBGRID_SIZE;
for (int i = subgridRowStart; i < subgridRowStart + SUBGRID_SIZE; i++) {
for (int j = subgridColStart; j < subgridColStart + SUBGRID_SIZE; j++) {
if (board[i][j] == number) {
return true;
}
}
}
return false;
}
/**
* Prints the Sudoku board
*
* @param board the Sudoku board
*/
public static void printBoard(int[][] board) {
for (int row = 0; row < GRID_SIZE; row++) {
if (row % SUBGRID_SIZE == 0 && row != 0) {
System.out.println("-----------");
}
for (int col = 0; col < GRID_SIZE; col++) {
if (col % SUBGRID_SIZE == 0 && col != 0) {
System.out.print("|");
}
System.out.print(board[row][col]);
}
System.out.println();
}
}
}

View File

@@ -1,169 +0,0 @@
package com.thealgorithms.puzzlesandgames;
/**
* A class that provides methods to solve Sudoku puzzles of any n x n size
* using a backtracking approach, where n must be a perfect square.
* The algorithm checks for safe number placements in rows, columns,
* and subgrids (which are sqrt(n) x sqrt(n) in size) and recursively solves the puzzle.
* Though commonly used for 9x9 grids, it is adaptable to other valid Sudoku dimensions.
*/
final class Sudoku {
private Sudoku() {
}
/**
* Checks if placing a number in a specific position on the Sudoku board is safe.
* The number is considered safe if it does not violate any of the Sudoku rules:
* - It should not be present in the same row.
* - It should not be present in the same column.
* - It should not be present in the corresponding 3x3 subgrid.
* - It should not be present in the corresponding subgrid, which is sqrt(n) x sqrt(n) in size (e.g., for a 9x9 grid, the subgrid will be 3x3).
*
* @param board The current state of the Sudoku board.
* @param row The row index where the number is to be placed.
* @param col The column index where the number is to be placed.
* @param num The number to be placed on the board.
* @return True if the placement is safe, otherwise false.
*/
public static boolean isSafe(int[][] board, int row, int col, int num) {
// Check the row for duplicates
for (int d = 0; d < board.length; d++) {
if (board[row][d] == num) {
return false;
}
}
// Check the column for duplicates
for (int r = 0; r < board.length; r++) {
if (board[r][col] == num) {
return false;
}
}
// Check the corresponding 3x3 subgrid for duplicates
int sqrt = (int) Math.sqrt(board.length);
int boxRowStart = row - row % sqrt;
int boxColStart = col - col % sqrt;
for (int r = boxRowStart; r < boxRowStart + sqrt; r++) {
for (int d = boxColStart; d < boxColStart + sqrt; d++) {
if (board[r][d] == num) {
return false;
}
}
}
return true;
}
/**
* Solves the Sudoku puzzle using backtracking.
* The algorithm finds an empty cell and tries placing numbers
* from 1 to n, where n is the size of the board
* (for example, from 1 to 9 in a standard 9x9 Sudoku).
* The algorithm finds an empty cell and tries placing numbers from 1 to 9.
* The standard version of Sudoku uses numbers from 1 to 9, so the algorithm can be
* easily modified for other variations of the game.
* If a number placement is valid (checked via `isSafe`), the number is
* placed and the function recursively attempts to solve the rest of the puzzle.
* If no solution is possible, the number is removed (backtracked),
* and the process is repeated.
*
* @param board The current state of the Sudoku board.
* @param n The size of the Sudoku board (typically 9 for a standard puzzle).
* @return True if the Sudoku puzzle is solvable, false otherwise.
*/
public static boolean solveSudoku(int[][] board, int n) {
int row = -1;
int col = -1;
boolean isEmpty = true;
// Find the next empty cell
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 0) {
row = i;
col = j;
isEmpty = false;
break;
}
}
if (!isEmpty) {
break;
}
}
// No empty space left
if (isEmpty) {
return true;
}
// Try placing numbers 1 to n in the empty cell (n should be a perfect square)
// Eg: n=9 for a standard 9x9 Sudoku puzzle, n=16 for a 16x16 puzzle, etc.
for (int num = 1; num <= n; num++) {
if (isSafe(board, row, col, num)) {
board[row][col] = num;
if (solveSudoku(board, n)) {
return true;
} else {
// replace it
board[row][col] = 0;
}
}
}
return false;
}
/**
* Prints the current state of the Sudoku board in a readable format.
* Each row is printed on a new line, with numbers separated by spaces.
*
* @param board The current state of the Sudoku board.
* @param n The size of the Sudoku board (typically 9 for a standard puzzle).
*/
public static void print(int[][] board, int n) {
// Print the board in a nxn grid format
// if n=9, print the board in a 9x9 grid format
// if n=16, print the board in a 16x16 grid format
for (int r = 0; r < n; r++) {
for (int d = 0; d < n; d++) {
System.out.print(board[r][d]);
System.out.print(" ");
}
System.out.print("\n");
if ((r + 1) % (int) Math.sqrt(n) == 0) {
System.out.print("");
}
}
}
/**
* The driver method to demonstrate solving a Sudoku puzzle.
* A sample 9x9 Sudoku puzzle is provided, and the program attempts to solve it
* using the `solveSudoku` method. If a solution is found, it is printed to the console.
*
* @param args Command-line arguments (not used in this program).
*/
public static void main(String[] args) {
int[][] board = new int[][] {
{3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0},
};
int n = board.length;
if (solveSudoku(board, n)) {
print(board, n);
} else {
System.out.println("No solution");
}
}
}