File tree 1 file changed +47
-0
lines changed 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
3
+ Date: Dec 20, 2014
4
+ Problem: Sudoku Solver
5
+ Difficulty: Medium
6
+ Source: https://oj.leetcode.com/problems/sudoku-solver/
7
+ Notes:
8
+ Write a program to solve a Sudoku puzzle by filling the empty cells.
9
+ Empty cells are indicated by the character '.'.
10
+ You may assume that there will be only one unique solution.
11
+
12
+ Solution: back-tracking..
13
+ */
14
+ public class Solution {
15
+ public void solveSudoku (char [][] board ) {
16
+ solve (board );
17
+ }
18
+ boolean solve (char [][] board ){
19
+ for (int i = 0 ;i <9 ;i ++){
20
+ for (int j =0 ;j <9 ;j ++){
21
+ if (board [i ][j ]=='.' ){
22
+ for (char ch = '1' ;ch <='9' ;ch ++){
23
+ board [i ][j ]=ch ;
24
+ if (isValidSudoKu (board ,i ,j )&&solve (board )) return true ;
25
+ board [i ][j ]='.' ;
26
+ }
27
+ return false ;
28
+ }
29
+ }
30
+ }
31
+ return true ;
32
+ }
33
+ boolean isValidSudoKu (char [][] board , int x , int y ){
34
+ for (int i = 0 ; i <9 ; i ++){
35
+ if (i !=y &&board [x ][i ]==board [x ][y ]) return false ;
36
+ }
37
+ for (int i =0 ;i <9 ;i ++){
38
+ if (i !=x &&board [i ][y ]==board [x ][y ]) return false ;
39
+ }
40
+ for (int i =3 *(x /3 );i <3 *(x /3 )+3 ;i ++){
41
+ for (int j =3 *(y /3 );j <3 *(y /3 )+3 ;j ++){
42
+ if (i !=x &&j !=y &&board [i ][j ]==board [x ][y ]) return false ;
43
+ }
44
+ }
45
+ return true ;
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments