Write a program in Java that solves a Sudoku puzzle. The program should take an incomplete 9x9 grid and return a completed solution. The grid contains numbers from 1 to 9, and the program must use backtracking to solve the puzzle.
Assistant
Sure! Below is a Java program that solves a Sudoku puzzle using the backtracking algorithm. Backtracking is a recursive algorithm that tries to fill the Sudoku grid by trying all possible numbers (from 1 to 9) in empty cells and backtracks when it encounters a conflict.
How the Program Works
Input Grid: The Sudoku puzzle is represented as a 9x9 2D array. Empty cells are denoted by 0.
Backtracking Algorithm:
Find Empty Cell: The program searches for an empty cell (denoted by 0). If no empty cells are found, the puzzle is solved.
Try Numbers 1-9: For the found empty cell, the program tries numbers from 1 to 9.
Check Validity: For each number, the program checks if placing the number in the current cell is valid (i.e., the number doesn't already exist in the same row, column, or 3x3 subgrid).
Recursion: If the number is valid, it's placed in the cell, and the program recursively attempts to solve the rest of the grid.
Backtrack: If placing the number leads to a dead end (no valid number can be placed in a subsequent cell), the program resets the cell to 0 and tries the next number.
Solution: Once the grid is completely filled without conflicts, the solution is printed.
Java Implementation
java
public class SudokuSolver {
// Size of the Sudoku grid
private static final int GRID_SIZE = 9;
public static void main(String[] args) {
// Example Sudoku puzzle (0 denotes empty cells)
int[][] board = {
{7, 0, 2, 0, 5, 0, 6, 0, 0},
{0, 0, 0, 0, 0, 3, 0, 0, 0},
{1, 0, 0, 0, 0, 9, 5, 0, 0},
{8, 0, 0, 0, 0, 0, 0, 9, 0},
{0, 4, 3, 0, 0, 0, 7, 5, 0},
{0, 9, 0, 0, 0, 0, 0, 0, 8},
{0, 0, 9, 7, 0, 0, 0, 0, 5},
{0, 0, 0, 2, 0, 0, 0, 0, 0},
{0, 0, 7, 0, 4, 0, 2, 0, 3}
};
System.out.println("Initial Sudoku Board:");
printBoard(board);
if (solveSudoku(board)) {
System.out.println("\nSolved Sudoku Board:");
printBoard(board);
} else {
System.out.println("No solution exists for the given Sudoku puzzle.");
}
}
/**
* Solves the Sudoku puzzle using backtracking.
* @param board 9x9 Sudoku board
* @return true if a solution exists, false otherwise
*/
public static boolean solveSudoku(int[][] board) {
// Find an empty cell
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
// Look for an empty cell
if (board[row][col] == 0) {
// Try numbers 1-9 in the empty cell
for (int num = 1; num <= 9; num++) {
// Check if it's safe to place the number
if (isSafe(board, row, col, num)) {
board[row][col] = num; // Place the number
// Recursively try to fill the rest of the board
if (solveSudoku(board)) {
return true;
}
// If placing num doesn't lead to a solution, backtrack
board[row][col] = 0;
}
}
// If no number can be placed in this cell, trigger backtracking
return false;
}
}
}
// If no empty cells are left, the puzzle is solved
return true;
}
/**
* Checks whether it's safe to place a number in a cell.
* It ensures the number is not already present in the current row, column, or 3x3 subgrid.
* @param board Sudoku board
* @param row Current row
* @param col Current column
* @param num Number to place
* @return true if safe, false otherwise
*/
public static boolean isSafe(int[][] board, int row, int col, int num) {
// Check row
for (int i = 0; i < GRID_SIZE; i++) {
if (board[row][i] == num) {
return false;
}
}
// Check column
for (int i = 0; i < GRID_SIZE; i++) {
if (board[i][col] == num) {
return false;
}
}
// Check 3x3 subgrid
int startRow = row - row % 3;
int startCol = col - col % 3;
for (int i = startRow; i < startRow + 3; i++) {
for (int j = startCol; j < startCol + 3; j++) {
if (board[i][j] == num) {
return false;
}
}
}
// If no conflicts, it's safe to place the number
return true;
}
/**
* Prints the Sudoku board in a readable format.
* @param board Sudoku board
*/
public static void printBoard(int[][] board) {
for (int row = 0; row < GRID_SIZE; row++) {
if (row % 3 == 0 && row != 0) {
System.out.println("------+-------+------");
}
for (int col = 0; col < GRID_SIZE; col++) {
if (col % 3 == 0 && col != 0) {
System.out.print("| ");
}
if (col == 8) {
System.out.println(board[row][col]);
} else {
System.out.print(board[row][col] + " ");
}
}
}
}
}
How to Use the Program
Input Puzzle: Modify the board 2D array in the main method with your Sudoku puzzle. Use 0 to denote empty cells.
Run the Program: Compile and run the Java program. If a solution exists, it will print the solved Sudoku board. Otherwise, it will indicate that no solution exists.
Note: The provided example might have multiple solutions or require a unique puzzle to work correctly. Ensure that the input puzzle has a valid and unique solution for the backtracking algorithm to find it efficiently.
Additional Notes
Performance: The backtracking algorithm is efficient for standard Sudoku puzzles. However, for more complex or larger Sudoku variations, optimizations or different algorithms might be necessary.
Validation: This program assumes that the input Sudoku puzzle is valid (i.e., no conflicting numbers in the initial setup). You might want to add additional validation if necessary.
Feel free to customize and enhance the program based on your requirements!