关闭

FTPrep, 37 Sukodu Solver

85人阅读 评论(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;
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11235次
    • 积分:1931
    • 等级:
    • 排名:千里之外
    • 原创:179篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条