forked from codemistic/Web-Development
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsol.java
More file actions
68 lines (61 loc) · 1.53 KB
/
sol.java
File metadata and controls
68 lines (61 loc) · 1.53 KB
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
class Solution {
public void solveSudoku(char[][] board) {
solve(board);
}
static boolean solve(char[][] board){
int n = board.length;
int row = -1;
int col = -1;
boolean noEmptyLeft = true;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(board[i][j]=='.'){
row = i;
col = j;
noEmptyLeft = false;
break;
}
}
if(!noEmptyLeft)
break;
}
if(noEmptyLeft)
return true;
//solved
//backtrack
for(int number = 1;number<=9;number++){
if(isSafe(board,row,col,number)){
board[row][col]= (char)(number +'0');
if(solve(board)){
return true;
}
else{
board[row][col] = '.';
}
}
}
return false;
}
private static boolean isSafe(char[][] board,int row,int col,int num){
for(int i=0;i<board.length;i++){
if(num == (board[row][i]-'0')){
return false;
}
}
for(int i=0;i<board.length;i++){
if(num == (board[i][col]-'0')){
return false;
}
}
int sqrt = (int)Math.sqrt(board.length);
int rowStart = row - row%sqrt;
int colStart = col - col%sqrt;
for(int i=rowStart;i<rowStart+sqrt;i++){
for(int j=colStart;j<colStart+sqrt;j++){
if(num == (board[i][j] - '0'))
return false;
}
}
return true;
}
}