-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudooku.java
More file actions
79 lines (70 loc) · 2.23 KB
/
Sudooku.java
File metadata and controls
79 lines (70 loc) · 2.23 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
public class Sudooku {
public static boolean issafe(int sudoku[][], int row, int col, int digit) {
// Condition for column
for (int i = 0; i < 9; i++) {
if (sudoku[i][col] == digit) {
return false;
}
}
// Condition for row
for (int j = 0; j < 9; j++) {
if (sudoku[row][j] == digit) {
return false;
}
}
// Condition for grid
int startrow = (row / 3) * 3;
int startcol = (col / 3) * 3;
for (int i = startrow; i < startrow + 3; i++) {
for (int j = startcol; j < startcol + 3; j++) {
if (sudoku[i][j] == digit) {
return false;
}
}
}
return true;
}
public static boolean sudokusolver(int sudoku[][], int row, int col) {
// Base Case
if (row == 9) {
return true;
}
// recursion
int nextrow = row, nextcol = col + 1;
if (col + 1 == 9) {
nextrow = row + 1;
nextcol = 0;
}
// if cell is already filled, skip it
if (sudoku[row][col] != 0) {
return sudokusolver(sudoku, nextrow, nextcol);
}
// Try placing digits 1-9
for (int digit = 1; digit <= 9; digit++) {
if (issafe(sudoku, row, col, digit)) {
sudoku[row][col] = digit;
if (sudokusolver(sudoku, nextrow, nextcol)) {
return true;
}
sudoku[row][col] = 0;
}
}
return false;
}
public static void main(String[] args) {
int[][] sudokuGrid = {
{ 5, 3, 0, 0, 7, 0, 0, 0, 0 },
{ 6, 0, 0, 1, 9, 5, 0, 0, 0 },
{ 0, 9, 8, 0, 0, 0, 0, 6, 0 },
{ 8, 0, 0, 0, 6, 0, 0, 0, 3 },
{ 4, 0, 0, 8, 0, 3, 0, 0, 1 },
{ 7, 0, 0, 0, 2, 0, 0, 0, 6 },
{ 0, 6, 0, 0, 0, 0, 2, 8, 0 },
{ 0, 0, 0, 4, 1, 9, 0, 0, 5 },
{ 0, 0, 0, 0, 8, 0, 0, 7, 9 }
};
if (sudokusolver(sudokuGrid, 0, 0)) {
System.out.println("Solution exist");
}
}
}