FTPrep, 37 Sukodu Solver

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;
    }
}


阅读更多
个人分类: FTPrep
上一篇FTPrep, 36 Valid Sudoku
下一篇FTPrep, 38 Read and Count
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭