题目要求
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
题解
class Solution {
public void solveSudoku(char[][] board) {
backTraceing(board);
}
private boolean backTraceing(char[][] board){
for(int i = 0; i < board.length;i++){
for(int j = 0; j < board.length;j++){
if(board[i][j] < '0' || board[i][j] > '9'){
for(char k = '1'; k <= '9'; k++){
board[i][j] = k;
if(isTrue(board,i,j)){
if(!backTraceing(board)){
board[i][j] = '.';
}else{
return true;
}
}else{
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
private boolean isTrue(char[][] board,int row,int column){
return isVailed(board,row,column,true) && isVailed(board,row,column,false) && isVailed(board,row,column);
}
private boolean isVailed(char[][] board,int row,int column,boolean isRow){
boolean[] marked = new boolean[board.length + 1];
for(int i = 0; i < board.length; i++){
int current = -2;
if(isRow){
current = board[row][i] - '0';
}
else{
current = board[i][column] - '0';
}
current = current > 0 ? current : 0;
if(current > 0 && marked[current]) return false;
marked[current] = true;
}
return true;
}
private boolean isVailed(char[][] board,int row,int column){
row = (row / 3) * 3;
column = (column / 3) * 3;
boolean[] marked = new boolean[board.length + 1];
for(int i = row; i < row + 3;i++){
for(int j = column; j < column + 3;j++){
int current = board[i][j] - '0';
current = current > 0 ? current : 0;
if(current > 0 && marked[current]) return false;
marked[current] = true;
}
}
return true;
}
}