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.
Answer:
public class Solution {
public void solveSudoku(char[][] board) {
int len = board.length;
if(len==0) return;
DFS(board);
}
public boolean DFS(char[][] board){
int len = board.length;
for(int i=0;i<len;++i){
for(int j=0;j<len;++j){
if(board[i][j] == '.'){
for(int k=1;k<=9;++k){
if(validStep(board,k,i,j)==true){
board[i][j] = (char)(k+'0');
if(DFS(board)==true){
return true;
}
}
}
board[i][j] = '.'; //backtrack!!!
return false;
}
}
}
return true;
}
public boolean validStep(char[][]board, int k, int i, int j){
for(int m=0;m<9;++m){
if(board[i][m]!='.' && m!=j && ((board[i][m]-'0') ==k)){
return false;
}
if(board[m][j]!='.' && m!=i && ((board[m][j]-'0') ==k)){
return false;
}
}
for(int n=i/3*3;n<(i/3*3+3);++n){
for(int q=j/3*3;q<(j/3*3+3);++q){
if(board[n][q]!='.' && (n!=i || q!=j) && ((board[n][q]-'0') ==k)){
return false;
}
}
}
return true;
}
}
No comments:
Post a Comment