-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
67 lines (67 loc) · 1.89 KB
/
Solution.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
public class Solution {
public void solveSudoku(char[][] board) {
//true表示需要填的
boolean[][] flag=new boolean[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
flag[i][j]=board[i][j]=='.';
}
}
for (int i = 0; i < 81;) {
int x=i/9;
int y=i%9;
if (flag[x][y]) {
if (board[x][y]=='.') {
board[x][y]='1';
if (f(board,x,y,board[x][y])) {
i++;
}
}else if(board[x][y]<'9'){
board[x][y]++;
if (f(board,x,y,board[x][y])) {
i++;
}
}else {
//回退
while ((!flag[x][y])||board[x][y]=='9') {
if (flag[x][y]) {
board[x][y]='.';
}
i--;
if (i<0) {
return ;
}
x=i/9;
y=i%9;
}
}
}else {
i++;
}
}
}
public boolean f(char[][] board,int x,int y,char val){
int a=x/3;
int b=y/3;
for (int i = 0; i < 9; i++) {
if (i!=y) {
if (board[x][i]==val) {
return false;
}
}
if (x!=i) {
if (board[i][y]==val) {
return false;
}
}
int ax=i/3;
int by=i%3;
if (x!=a*3+ax||y!=b*3+by) {
if (board[a*3+ax][b*3+by]==val) {
return false;
}
}
}
return true;
}
}