-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathSudokuSolver.java
More file actions
90 lines (76 loc) · 2.56 KB
/
SudokuSolver.java
File metadata and controls
90 lines (76 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.thealgorithms.backtracking;
/**
* Sudoku Solver using Backtracking Algorithm.
* Solves a 9x9 Sudoku puzzle by filling empty cells with valid digits (1-9).
*
* @author prasanth-30011
*/
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() {
// Prevent instantiation
}
/**
* Public method to solve a Sudoku puzzle.
*
* @param board 9x9 Sudoku grid (0 means empty)
* @return true if 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 that applies backtracking.
*
* @param board Sudoku board
* @return true if solved, 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;
}
board[row][col] = EMPTY_CELL; // Backtrack
}
}
return false; // No number fits here
}
}
}
return true; // Solved completely
}
private static boolean isValidPlacement(int[][] board, int row, int col, int number) {
// Row and column check
for (int i = 0; i < GRID_SIZE; i++) {
if (board[row][i] == number || board[i][col] == number) {
return false;
}
}
// Subgrid check
int startRow = (row / SUBGRID_SIZE) * SUBGRID_SIZE;
int startCol = (col / SUBGRID_SIZE) * SUBGRID_SIZE;
for (int r = 0; r < SUBGRID_SIZE; r++) {
for (int c = 0; c < SUBGRID_SIZE; c++) {
if (board[startRow + r][startCol + c] == number) {
return false;
}
}
}
return true;
}
}