# FTPrep, 37 Sukodu Solver

155人阅读 评论(0)

TODO: the explanation for the flow

1, recursive function: 3 key points

2, naming is important for logic and debugging, always having a good variable name

3, one-time bug free is left to do, first time is xxx minute and second

public class Solution {
public void solveSudoku(char[][] board) {
helper(board, 0, 0);
}

private boolean helper(char[][] board, int row, int col){
if(col==9) return helper(board, row+1, 0);
if(row==9) return true;
if(board[row][col]=='.'){
for(int k=1; k<=9; k++){
board[row][col] = (char)('0'+ k);
if(isValid(board, row, col, board[row][col])){
if(helper(board, row, col+1)) return true;
}
board[row][col]='.';
}
return false;
}
else return helper(board, row, col+1);
}

private boolean isValid(char[][] board, int i, int j, char ch){
for(int col=0; col<board[0].length; col++){
if(col!=j&& ch==board[i][col]) return false;
}
for(int row=0; row<board.length; row++){
if(row!=i&& ch==board[row][j]) return false;
}
for(int row=i/3*3; row<i/3*3 +3; row++){
for(int col=j/3*3; col<j/3*3+3; col++){
if((row!=i || col!=j) && ch==board[row][col]) return false;
}
}
return true;
}
}

个人资料
等级：
访问量： 2万+
积分： 2510
排名： 1万+
文章存档