题目描述
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...
- 思路
填充数独。
设置返回值用于标记是否已找到最终的结果并一步一步返回递归出口。
public class Solution {
public void solveSudoku(char[][] board) {
if(board == null || board[0].length == 0)
return ;
boolean[][] row = new boolean[10][10];
boolean[][] col = new boolean[10][10];
boolean[][] fix = new boolean[10][10];
for(int i=0; i<board.length; i++){
for(int j=0; j<board[0].length; j++){
if(board[i][j] != '.'){
int ch = board[i][j] - '0';
row[i][ch] = true;
col[j][ch] = true;
int cnt = i/3*3 + j/3;
fix[cnt][ch] = true;
}
}
}
getAns(board, 0, 0, row, col, fix);
}
public boolean getAns(char[][] map, int n, int m,
boolean[][] row, boolean[][] col, boolean[][] fix){
if(m >= 9){
m = 0;
n ++;
}
if(n >= 9)
return true;
if(map[n][m] != '.'){
return getAns(map, n, m+1, row, col, fix);
}else{
for(int i=1; i<=9; i++){
int cnt = n/3*3 + m/3;
if(row[n][i] || col[m][i] || fix[cnt][i])
continue;
map[n][m] = (char)('0' + i);
row[n][i] = true;
col[m][i] = true;
fix[cnt][i] = true;
if(getAns(map, n, m+1, row, col, fix))
return true;
map[n][m] = '.';
row[n][i] = false;
col[m][i] = false;
fix[cnt][i] = false;
}
}
return false;
}
}