您的位置:首页 > 其它

LeetCode-----37. Sudoku Solver(解数读)

2016-09-29 15:26 549 查看
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 Solution {
public void solveSudoku(char[][] board){
solve(board);
}

public boolean solve(char[][] board) {
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++){
if(board[i][j] != '.'){
continue;
}
for(int k = 1; k <= 9; k++){
board[i][j] = (char) (k + '0');
if (isValid(board, i, j) && solve(board)){
return true;
}
board[i][j] = '.';
}
return false;
}
}
return true;
}

public boolean isValid(char[][] board, int a, int b){
Set<Character> contained = new HashSet<Character>();
for(int j=0;j<9;j++){
if(contained.contains(board[a][j])) return false;
if(board[a][j]>'0' && board[a][j]<='9')
contained.add(board[a][j]);
}

contained = new HashSet<Character>();
for(int j=0;j<9;j++){
if (contained.contains(board[j][b])) {
return false;
}
if (board[j][b]>'0' && board[j][b]<='9') {
contained.add(board[j][b]);
}
}

contained = new HashSet<Character>();
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++){
int x = a / 3 * 3 + m, y = b / 3 * 3 + n;
if (contained.contains(board[x][y])) {
return false;
}
if (board[x][y] > '0' && board[x][y] <= '9') {
contained.add(board[x][y]);
}
}
}

return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: