原题:
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.
解题思路:使用回溯的方法,对每一个小格子的每一种可能性进行试探
private int[][] rowValid;//表示第i行数字j是否已经使用
private int[][] colValid;//表示第i列数字j是否已经使用
private int[][] subBoxValid;//表示第i个小格子数字j是否已经使用
public void solveSudoku(char[][] board) {
rowValid = new int[9][10];
colValid = new int[9][10];
subBoxValid = new int[9][10];
for(int i=0; i<9; i++)
for(int j=0; j<9; j++)
if(board[i][j] != '.') {
fill(i, j, board[i][j]-'0');
}
solveSudoKuImpl(board, 0);
}
private boolean solveSudoKuImpl(char[][] board, int index) {
//当前填充到第index个格子
if(index>80)
return true;
int i = index/9;//行号
int j = index - i*9;//列号
if(board[i][j] != '.')
return solveSudoKuImpl(board, index+1);
for(char val='1'; val<='9'; val++) {//试探每一种可能性
if(isValid(i, j, val-'0')) {
board[i][j] = val; //进行填充
fill(i, j, val-'0');
if(solveSudoKuImpl(board, index+1)) return true;//继续填充下一个格子
clear(i, j, val-'0');//当前数字不符合要求,清除状态,进行回溯
}
}
board[i][j] = '.';//都不符合要求,回复起始状态
return false;
}
//判断第row行,第col列填充val是否符合要求
private boolean isValid(int row, int col, int val) {
if(rowValid[row][val] == 0 &&
colValid[col][val] == 0 &&
subBoxValid[(row/3)*3+col/3][val] == 0 ) {
return true;
}
return false;
}
//更新填充状态
private void fill(int row, int col, int val) {
rowValid[row][val] = 1;
colValid[col][val] = 1;
subBoxValid[(row/3)*3+col/3][val] = 1;
}
//清除填充状态
private void clear(int row, int col, int val) {
rowValid[row][val] = 0;
colValid[col][val] = 0;
subBoxValid[(row/3)*3+col/3][val] = 0;
}