Skip to content

Commit 35b2bfc

Browse files
committed
Add additional check for valid board
1 parent 28d9cd3 commit 35b2bfc

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

src/main/java/com/thealgorithms/backtracking/SudokuSolver.java

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public static boolean isValidMove(final int[][] board, final int row, final int
5454
* @param board The 9x9 Sudoku board
5555
* @return true if the puzzle is solved, false if no solution exists
5656
*/
57-
public static boolean solveSudoku(final int[][] board) {
57+
public static boolean solveSudokuHelper(final int[][] board) {
5858
// Traverse the board
5959
for (int row = 0; row < 9; row++) {
6060
for (int col = 0; col < 9; col++) {
@@ -80,6 +80,69 @@ public static boolean solveSudoku(final int[][] board) {
8080
return true; // Sudoku is solved if no empty cells are left
8181
}
8282

83+
/**
84+
* Check if the given Sudoku board is valid.
85+
* A valid board has no duplicate numbers in rows, columns, or 3x3 subgrids.
86+
*
87+
* @param board The 9x9 Sudoku board
88+
* @return true if the board is valid, false otherwise
89+
*/
90+
public static boolean isValidSudoku(final int[][] board) {
91+
// Check each row
92+
for (int i = 0; i < 9; i++) {
93+
boolean[] row = new boolean[10];
94+
for (int j = 0; j < 9; j++) {
95+
if (board[i][j] != 0) {
96+
if (row[board[i][j]]) {
97+
return false;
98+
}
99+
row[board[i][j]] = true;
100+
}
101+
}
102+
}
103+
104+
// Check each column
105+
for (int i = 0; i < 9; i++) {
106+
boolean[] col = new boolean[10];
107+
for (int j = 0; j < 9; j++) {
108+
if (board[j][i] != 0) {
109+
if (col[board[j][i]]) {
110+
return false;
111+
}
112+
col[board[j][i]] = true;
113+
}
114+
}
115+
}
116+
117+
// Check each 3x3 subgrid
118+
for (int i = 0; i < 9; i += 3) {
119+
for (int j = 0; j < 9; j += 3) {
120+
boolean[] grid = new boolean[10];
121+
for (int k = 0; k < 3; k++) {
122+
for (int l = 0; l < 3; l++) {
123+
if (board[i + k][j + l] != 0) {
124+
if (grid[board[i + k][j + l]]) {
125+
return false;
126+
}
127+
grid[board[i + k][j + l]] = true;
128+
}
129+
}
130+
}
131+
}
132+
}
133+
134+
return true;
135+
}
136+
137+
public static boolean solveSudoku(final int[][] board) {
138+
// Check if the board is valid
139+
if (!isValidSudoku(board)) {
140+
return false;
141+
}
142+
143+
return solveSudokuHelper(board);
144+
}
145+
83146
/**
84147
* Print the current state of the Sudoku board.
85148
*

0 commit comments

Comments
 (0)