1
+ class Solution {
2
+ private char [][] board ;
3
+ private boolean [][] rows ;
4
+ private boolean [][] cols ;
5
+ private boolean [][] subBox ;
6
+
7
+ public void solveSudoku (char [][] board ) {
8
+ this .board = board ;
9
+ this .rows = new boolean [9 ][9 ];
10
+ this .cols = new boolean [9 ][9 ];
11
+ this .subBox = new boolean [9 ][9 ];
12
+ int val ;
13
+ for (int i = 0 ; i < 9 ; i ++) {
14
+ for (int j = 0 ; j < 9 ; j ++) {
15
+ if (board [i ][j ] != '.' ) {
16
+ val = board [i ][j ] - '0' ;
17
+ rows [i ][val - 1 ] = true ;
18
+ cols [j ][val - 1 ] = true ;
19
+ subBox [(i / 3 ) * 3 + j / 3 ][val - 1 ] = true ;
20
+ }
21
+ }
22
+ }
23
+ fillSudoku (0 , 0 );
24
+ }
25
+
26
+ private boolean fillSudoku (int i , int j ) {
27
+ if (i == 9 ) return true ;
28
+ int x = i , y = j ;
29
+ if (y == 8 ) {
30
+ x ++;
31
+ y = 0 ;
32
+ } else y ++;
33
+ if (board [i ][j ] == '.' ) {
34
+ for (int k = 1 ; k <= 9 ; k ++) {
35
+ if (!rows [i ][k - 1 ] && !cols [j ][k - 1 ] && !subBox [(i / 3 ) * 3 + j / 3 ][k - 1 ]) {
36
+ rows [i ][k - 1 ] = true ;
37
+ cols [j ][k - 1 ] = true ;
38
+ subBox [(i / 3 ) * 3 + j / 3 ][k - 1 ] = true ;
39
+ if (fillSudoku (x , y )) {
40
+ board [i ][j ] = (char ) (k + '0' );
41
+ return true ;
42
+ }
43
+ rows [i ][k - 1 ] = false ;
44
+ cols [j ][k - 1 ] = false ;
45
+ subBox [(i / 3 ) * 3 + j / 3 ][k - 1 ] = false ;
46
+ }
47
+ }
48
+ return false ;
49
+ } else return fillSudoku (x , y );
50
+ }
51
+ }
0 commit comments