-
Notifications
You must be signed in to change notification settings - Fork 1
/
LC37_SudokuSolver.java
63 lines (59 loc) · 1.63 KB
/
LC37_SudokuSolver.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
import java.util.Arrays;
class LC37_SudokuSolver {
//�� Ʈ��ŷ
//������ � �� ����
// ��� ����� ���� �����ϸ鼭, ������ ��ȿ���� ����� �ʴ��� Ȯ���ϸ鼭 Ž��
// ���̻� ���ư����� ������
// ��ĭ �ڷ� ����
public void solveSudoku(char[][] board) {
backtrack(board, 0);
}
// => �ڵ��̻�����. �ٽ�Ǯ��.
public boolean backtrack(char[][] board, int idx) {
if(idx==81) return true;
int row = idx / 9;
int col = idx % 9;
char cur = board[row][col];
if(cur != '.') {
return backtrack(board, idx+1);
}else {
for(int i=1; i<=9; i++) {
board[row][col] = (char)i;
if(isValidSudoku(board)) {
boolean b = backtrack(board, idx + 1);
if(b) return b;
}
}
board[row][col] = '.';
return false;
}
}
public static boolean isValidSudoku(char[][] board) {
boolean[] b = new boolean[9];
//���� ����, ����/����/������
for(int i=0; i<3; i++) {
//������ ��Ģ
for(int j=0; j<9; j++) {
Arrays.fill(b, false);
for(int k=0; k<9; k++) {
char cur= '.';
if(i == 0) {
//����
cur=board[j][k];
}else if(i == 1) {
//����
cur=board[k][j];
}else {
//������
cur = board[j/3*3 + k/3][j%3*3 + k%3];
}
if(cur=='.') continue;
int val = Character.getNumericValue(cur);
if(b[val-1]) return false;
b[val-1] = true;
}
}
}
return true;
}
}