题目
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.
分析
回溯法,挨个试
不用考虑时间复杂度。这种解放人类大脑的题基本都需要计算机累一点。
写了一个不忍直视的递归。
应该会有简化的方法。
class Solution {
public static void solveSudoku(char[][] board) {
if (board[0][0] != '.') {
testAdd(board, 0, 0);
} else {
char init = '1';
while (init <= '9') {
board[0][0] = init;
if (testAdd(board, 0, 0)) {
break;
} else {
init++;
}
}
}
for (int i = 0; i < 9; i++) {
System.out.println(Arrays.toString(board[i]));
}
}
public static boolean testAdd(char[][] board, int x, int y) {
//验证xy位置的正确性
char cur = board[x][y];
for (int i = 0; i < 9; i++) {
if (board[i][y] == cur && i != x) {
return false;
}
if (board[x][i] == cur && i != y) {
return false;
}
}
int xblock = x / 3;
int yblock = y / 3;
for (int i = xblock * 3; i < xblock * 3 + 3; i++) {
for (int j = yblock * 3; j < yblock * 3 + 3; j++) {
if (board[i][j] == cur && ((i != x) || (j != y))) {
return false;
}
}
}
int newx = -1, newy = -1;
for (int i = x; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
newx = i;
newy = j;
break;
}
}
if (newx != -1) {
break;
}
}
if (newx == -1 && newy == -1) {
return true;
}
char testchar = '0';
do {
testchar++;
board[newx][newy] = testchar;
if (testAdd(board, newx, newy) == true) {
return true;
}
} while (testchar < '9');
board[newx][newy] = '.';
return false;
}
}