题目描述:
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.
思路解析:
- 回溯法,从一条路往前走,能进则进,不能进就后退,换一条路
- 这个问题的解决方法也是一样的,需要从‘1’到‘9’填数字,满足直接返回true;不满足就回退到‘.’
- 遍历每一行,每一列,只要是‘.’的,就要尝试填入‘1’到‘9’
- 注意判断是否是空的条件,首先判断行,i;然后判断列,j;然后判断每个小block是否合法。都判断完毕,就是真正的答案了。
代码:
public class Solution {
public void solveSudoku(char[][] board) {
if(board == null||board.length==0)
return ;
helper(board);
}
private boolean helper(char[][] board){
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]=='.'){
for(char num = '1';num<='9';num++){
if(isValid(board,i,j,num)){
board[i][j]=num;
if(helper(board)){
return true;
}else{
board[i][j]='.';
}
}
}
return false;//全部放过后还是没有正确的
}
}
}
return true;//全部遍历后找不到有‘.’的,都写完啦,说明对了
}
private boolean isValid(char[][] board,int i,int j,char c){
for(int row=0;row<9;row++){//行是否合法
if(board[row][j]==c)
return false;
}
for(int col=0;col<9;col++){//列是否合法
if(board[i][col]==c)
return false;
}
for(int row=i/3*3;row<i/3*3+3;row++){//小的block是否合法
for(int col=j/3*3;col<j/3*3+3;col++){
if(board[row][col]==c)
return false;
}
}
return true;
}
}