題目
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...
...and its solution numbers marked in red.
分析遞歸的方法,根據數獨規則剪枝。
代碼
public class SudokuSolver {
int N;
int subSize;
char[][] board;
public void solveSudoku(char[][] board) {
this.board = board;
N = board.length;
subSize = (int) Math.sqrt(N);
solve(0);
}
private boolean solve(int index) {
if (index == N * N) {
return true;
}
int x = index / N;
int y = index % N;
if (board[x][y] == '.') {
for (char c = '1'; c <= '9'; ++c) {
if (isValidCell(x, y, c)) {
board[x][y] = c;
if (solve(index + 1)) {
return true;
}
board[x][y] = '.';
}
}
} else {
return solve(index + 1);
}
return false;
}
private boolean isValidCell(int x, int y, char c) {
// row
for (int column = 0; column < N; ++column) {
if (board[x][column] == c) {
return false;
}
}
// column
for (int row = 0; row < N; ++row) {
if (board[row][y] == c) {
return false;
}
}
// subboard
int originRow = (x / subSize) * subSize;
int originColumn = (y / subSize) * subSize;
for (int i = 0; i < N; ++i) {
int row = originRow + i / subSize;
int column = originColumn + i % subSize;
if (board[row][column] == c) {
return false;
}
}
return true;
}
}