Skip to content

Commit f554ae0

Browse files
author
khalidx3
committed
Added Sudoku Solver backtracking algorithm with test cases
1 parent 7e29be3 commit f554ae0

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package main.java.com.thealgorithms.backtracking;
2+
3+
public class SudokuSolver {
4+
public static boolean sudokuSolver(int sudoku[][], int row, int col) {
5+
// base case
6+
if (row == 9) {
7+
return true;
8+
}
9+
// recursion
10+
int nextRow = row, nextCol = col + 1;
11+
if (col + 1 == 9) {
12+
nextRow = row + 1;
13+
nextCol = 0;
14+
}
15+
if (sudoku[row][col] != 0) {
16+
return sudokuSolver(sudoku, nextRow, nextCol);
17+
}
18+
for (int digit = 1; digit <= 9; digit++) {
19+
if (isSafe(sudoku, row, col, digit)) {
20+
sudoku[row][col] = digit;
21+
22+
if (sudokuSolver(sudoku, nextRow, nextCol)) {
23+
return true;
24+
}
25+
sudoku[row][col] = 0;
26+
}
27+
}
28+
29+
return false;
30+
}
31+
32+
public static boolean isSafe(int sudoku[][], int row, int col, int digit) {
33+
// col
34+
for (int i = 0; i <= 8; i++) {
35+
if (sudoku[i][col] == digit) {
36+
return false;
37+
}
38+
}
39+
// row
40+
for (int j = 0; j <= 8; j++) {
41+
if (sudoku[row][j] == digit) {
42+
return false;
43+
}
44+
}
45+
// grid
46+
int sr = (row / 3) * 3;
47+
int sc = (col / 3) * 3;
48+
for (int i = sr; i < sr + 3; i++) {
49+
for (int j = sc; i < sr + 3; i++) {
50+
if (sudoku[i][j] == digit) {
51+
return false;
52+
}
53+
}
54+
}
55+
return true;
56+
}
57+
58+
public static void print(int sudoku[][]) {
59+
for (int i = 0; i < 9; i++) {
60+
for (int j = 0; j < 9; j++) {
61+
System.out.print(sudoku[i][j] + " ");
62+
}
63+
System.out.println();
64+
}
65+
}
66+
67+
public static void main(String[] args) {
68+
int sudoku[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
69+
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 },
70+
{ 0, 8, 7, 0, 0, 0, 0, 3, 1 },
71+
{ 0, 0, 3, 0, 1, 0, 0, 8, 0 },
72+
{ 9, 0, 0, 8, 6, 3, 0, 0, 5 },
73+
{ 0, 5, 0, 0, 9, 0, 6, 0, 0 },
74+
{ 1, 3, 0, 0, 0, 0, 2, 5, 0 },
75+
{ 0, 0, 0, 0, 0, 0, 0, 7, 4 },
76+
{ 0, 0, 5, 2, 0, 6, 3, 0, 0 } };
77+
if (sudokuSolver(sudoku, 0, 0)) {
78+
79+
print(sudoku);
80+
} else {
81+
System.out.println("not valid");
82+
}
83+
}
84+
85+
}

0 commit comments

Comments
 (0)