-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.java
83 lines (69 loc) · 1.84 KB
/
code.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
import java.util.*;
public class code {
public static void display(int[][] board){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void solveSudoku(int[][] board, int i, int j) {
if( i == board.length){
display(board);
return;
}
int ni = 0; // ni: next i
int nj = 0; // nj: next j
if( j == board[0].length -1){
ni = i + 1;
nj = 0;
}else{
ni = i ;
nj = j + 1;
}
if( board[i][j] != 0){
solveSudoku(board, ni, nj);
}else{
for( int po= 1; po <= 9; po++){
if(isValid(board, i, j, po) == true){
board[i][j] = po;
solveSudoku(board, ni, nj);
board[i][j] = 0;
}
}
}
}
public static boolean isValid( int[][] board, int x, int y, int val){
for( int j = 0; j < board[0].length; j++){
if( board[x][j] == val){
return false;
}
}
for( int i=0 ; i< board.length; i++){
if( board[i][y] == val){
return false;
}
}
int smi = x / 3 * 3; // submatrix ka i
int smj = y / 3 * 3; // submatrix ka j
for(int i = 0; i < 3 ; i++){
for( int j = 0 ; j< 3; j++){
if( board[smi + i][smj + j] == val){
return false;
}
}
}
return true;
}
public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
int[][] arr = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
arr[i][j] = scn.nextInt();
}
}
solveSudoku(arr, 0, 0);
}
}