Skip to content

Commit 10ec6ec

Browse files
committed
Sudoku solver updated
1 parent 069d0a0 commit 10ec6ec

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

sudokuSolver/src/sudokuSolver.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
public class sudokuSolver {
2+
public static boolean solve(int[][] sudoku) {
3+
for (int i = 0; i < 9; i++) {
4+
for (int j = 0; j < 9; j++) {
5+
if (sudoku[i][j] == 0) {
6+
for (int n = 1; n <= 9; n++) {
7+
if (isSafe(i, j, n, sudoku)) {
8+
sudoku[i][j] = n;
9+
if (solve(sudoku)) return true;
10+
else sudoku[i][j] = 0;
11+
}
12+
}
13+
return false;
14+
}
15+
}
16+
}
17+
return true;
18+
}
19+
20+
public static boolean isSafe(int row, int col, int num, int[][] sudoku) {
21+
for (int i = 0; i < 9; i++) {
22+
if (sudoku[i][col] == num || sudoku[row][i] == num) return false;
23+
if (sudoku[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == num) return false;
24+
}
25+
return true;
26+
}
27+
28+
public static void main(String[] args) {
29+
int[][] sudoko = new int[][]{
30+
{5, 3, 0, 0, 7, 0, 0, 0, 0},
31+
{6, 0, 0, 1, 9, 5, 0, 0, 0},
32+
{0, 9, 8, 0, 0, 0, 0, 6, 0},
33+
{8, 0, 0, 0, 6, 0, 0, 0, 3},
34+
{4, 0, 0, 8, 0, 3, 0, 0, 1},
35+
{7, 0, 0, 0, 2, 0, 0, 0, 6},
36+
{0, 6, 0, 0, 0, 0, 2, 8, 0},
37+
{0, 0, 0, 4, 1, 9, 0, 0, 5},
38+
{0, 0, 0, 0, 8, 0, 0, 7, 9}
39+
};
40+
solve(sudoko);
41+
for (int i = 0; i < 9; i++) {
42+
for (int j = 0; j < 9; j++) {
43+
System.out.print(sudoko[i][j] + " ");
44+
}
45+
System.out.println();
46+
}
47+
}
48+
}

sudokuSolver/sudokuSolver.iml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" inherit-compiler-output="true">
4+
<exclude-output />
5+
<content url="file://$MODULE_DIR$">
6+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
7+
</content>
8+
<orderEntry type="inheritedJdk" />
9+
<orderEntry type="sourceFolder" forTests="false" />
10+
</component>
11+
</module>

0 commit comments

Comments
 (0)