-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudokuSol.java
88 lines (83 loc) · 2.06 KB
/
sudokuSol.java
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
80
81
82
83
84
85
86
87
88
import java.util.*;
class sudokuSol{
public static boolean isSafe(int[][] board,
int row, int col,
int num)
{
for (int d = 0; d < board.length; d++) {
if (board[row][d] == num) {
return false;
}
}
for (int r = 0; r < board.length; r++) {
if (board[r][col] == num) {
return false;
}
}
int sqrt = (int)Math.sqrt(board.length);
int boxRowStart = row - row % sqrt;
int boxColStart = col - col % sqrt;
for (int r = boxRowStart;
r < boxRowStart + sqrt; r++) {
for (int d = boxColStart;
d < boxColStart + sqrt; d++) {
if (board[r][d] == num) {
return false;
}
}
}
return true;
}
static boolean solve(int[][] s){
int row = -1;
int col = -1;
boolean isEmpty = true;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(s[i][j] == 0){
row=i;
col=j;
isEmpty = false;
break;
}
}
if(!isEmpty) break;
}
if(isEmpty){
return true;
}
for (int num = 1; num <= 9; num++) {
if (isSafe(s, row, col, num)) {
s[row][col] = num;
if (solve(s)) {
return true;
}
else {
s[row][col] = 0;
}
}
}
return false;
}
public static void main(String[] args){
int[][] sudoku = new int[9][9];
Scanner s = new Scanner(System.in);
// Empty cell is represented by 0
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
sudoku[i][j] = s.nextInt();
}
}
if(solve(sudoku)){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
System.out.printf("%d ",sudoku[i][j]);
}
System.out.println("");
}
}
else{
System.out.println("No solution");
}
}
}