码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode——37.解数独

时间:2020-06-30 10:39:23      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:数独   oar   board   continue   track   tco   img   com   das   

看了大佬的题解,茅塞顿开

public void solveSudoku(char[][] board) {
        if(board == null || board.length != 9 || board[0] == null || board[0].length != 9){
            return;
        }
        backtrack(board,0,0);


    }
    public boolean backtrack(char[][] board,int i ,int j){
        int m = 9,n = 9;
        if(j == n){
            return backtrack(board,i+1,0);
        }
        if(i == m){
            return true;
        }
        if(board[i][j] != ‘.‘){
            return backtrack(board,i,j+1);
        }
        for(char ch = ‘1‘;ch <= ‘9‘;ch++){
            if(!isValid(board,i,j,ch)){
                continue;
            }
            board[i][j] = ch;
            if(backtrack(board,i,j+1)){
                return true;
            }
            board[i][j] = ‘.‘;
        }
        return false;
    }

    private boolean isValid(char[][] board, int r, int c, char n) {
        for(int i = 0;i<9;i++){
            if(board[r][i] == n){
                return false;
            }
            if(board[i][c] == n){
                return false;
            }
            if(board[(r/3)*3+i/3][(c/3)*3+i%3] == n){
                return false;
            }
        }
        return true;
    }

技术图片

 

 ——2020.6.30

leetcode——37.解数独

标签:数独   oar   board   continue   track   tco   img   com   das   

原文地址:https://www.cnblogs.com/taoyuxin/p/13212174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!