Skip to content

Commit 66a771b

Browse files
author
khalidx3
committed
Add Sudoku Solver refactored to pass Build and Clang Format
1 parent 6d51709 commit 66a771b

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package main.java.com.thealgorithms.backtracking;
2+
3+
/**
4+
* Sudoku Solver using Backtracking Algorithm
5+
*
6+
* Solves a 9x9 Sudoku puzzle. All methods are static and class is final to
7+
* match
8+
* TheAlgorithms/Java repo conventions.
9+
*/
10+
public final class SudokuSolver {
11+
12+
private SudokuSolver() {
13+
} // Prevent instantiation
14+
15+
/**
16+
* Solves the Sudoku puzzle using backtracking.
17+
*
18+
* @param sudoku 9x9 Sudoku grid, empty cells are 0
19+
* @param row current row
20+
* @param col current column
21+
* @return true if solved, false otherwise
22+
*/
23+
public static boolean sudokuSolver(int[][] sudoku, int row, int col) {
24+
if (row == 9) {
25+
return true;
26+
}
27+
28+
int nextRow = row;
29+
int nextCol = col + 1;
30+
if (nextCol == 9) {
31+
nextRow = row + 1;
32+
nextCol = 0;
33+
}
34+
35+
if (sudoku[row][col] != 0) {
36+
return sudokuSolver(sudoku, nextRow, nextCol);
37+
}
38+
39+
for (int num = 1; num <= 9; num++) {
40+
if (isSafe(sudoku, row, col, num)) {
41+
sudoku[row][col] = num;
42+
if (sudokuSolver(sudoku, nextRow, nextCol)) {
43+
return true;
44+
}
45+
sudoku[row][col] = 0; // backtrack
46+
}
47+
}
48+
49+
return false;
50+
}
51+
52+
/**
53+
* Checks if placing num at (row, col) is safe.
54+
*
55+
* @param sudoku 9x9 Sudoku grid
56+
* @param row current row
57+
* @param col current column
58+
* @param num number to place
59+
* @return true if safe, false otherwise
60+
*/
61+
private static boolean isSafe(int[][] sudoku, int row, int col, int num) {
62+
for (int i = 0; i < 9; i++) {
63+
if (sudoku[row][i] == num || sudoku[i][col] == num) {
64+
return false;
65+
}
66+
}
67+
68+
int startRow = row - row % 3;
69+
int startCol = col - col % 3;
70+
for (int i = startRow; i < startRow + 3; i++) {
71+
for (int j = startCol; j < startCol + 3; j++) {
72+
if (sudoku[i][j] == num) {
73+
return false;
74+
}
75+
}
76+
}
77+
78+
return true;
79+
}
80+
81+
/**
82+
* Prints the Sudoku grid.
83+
*
84+
* @param sudoku 9x9 Sudoku grid
85+
*/
86+
public static void printSudoku(int[][] sudoku) {
87+
for (int i = 0; i < 9; i++) {
88+
for (int j = 0; j < 9; j++) {
89+
System.out.print(sudoku[i][j] + " ");
90+
}
91+
System.out.println();
92+
}
93+
}
94+
}

0 commit comments

Comments
 (0)