public class Solution {
public void solveSudoku(char[][] board) {
solveSudokuHelper(board);
}
private boolean solveSudokuHelper(char[][] board){
for(int i=0; i<board.length; i++)
for(int j=0; j<board.length; j++){
if(board[i][j] == '.'){
for(char k='1'; k<='9'; k++){
board[i][j] = k;
if(isValidSudoku(board,i,j) && solveSudokuHelper(board))
return true;
board[i][j]='.';
}
return false;
}
}
return true;
}
private boolean isValidSudoku(char[][] board, int x, int y){
for(int j=0; j<board.length; j++){
if(j!=y && board[x][j]==board[x][y])
return false;
}
for(int i=0; i<board.length; i++){
if(i!=x && board[i][y]==board[x][y])
return false;
}
for(int i=3*(x/3); i<3*(x/3)+3 ; i++)
for(int j=3*(y/3); j<3*(y/3)+3; j++)
{
if(<span style="background-color: rgb(255, 255, 51);">(i!=x||j!=y)</span> && board[i][j]==board[x][y])
return false;
}
return true;
}
}
分析:每遇到一个空格,验证【1-9】的每一个数字,如果该数字使得bord没有破坏数独的规律(横、竖、九宫)同时 通过该数字深度验证下一个空格的可能值
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.