/
SodukuSolver
87 lines (50 loc) · 1.94 KB
/
SodukuSolver
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
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
A sudoku puzzle...
leetcode solution
public class Solution {
public void solveSudoku(char[][] board) {
if(board == null || board.length == 0){
return ;
}
solve(board);
}
private boolean solve(char[][] board){
for(int i = 0 ; i < board.length ; i++){
for(int j = 0 ; j < board[0].length ; j++){
if(board[i][j] == '.'){
for(char num = '1' ; num<='9' ; num++){
if( isValid(board ,i,j,num)){
board[i][j]=num;
if(solve(board)){
return true; //If it's the solution return true
}else {
board[i][j] = '.';//otherwise go back
}
}
}
return false;
}
}
}
return true;
}
private boolean isValid(char[][] board , int i , int j , char c){
//check for col
for(int row = 0 ; row < 9 ; row++){
if( board[row][j] == c) {return false;}
}
//check for row
for(int col = 0 ; col < 9 ; col++){
if( board[i][col] ==c){ return false;}
}
//check for block
for(int row = i/3*3 ; row < i/3*3 +3 ; row++){
for(int col = j/3*3 ; col < j/3*3 +3 ; col++){
if(board[row][col] == c) return false;
}
}
return true;
}
}