37

/**
 * @param {character[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
var solveSudoku = function(board) {
    var emp = isEmpty(board)
    var r = emp[0]
    var c = emp[1]
    if(r === -1){
        return true
    } else{
        for(var d = 1; d < 10; d++){
            if(isValidSudoku(board, r, c, d.toString())){
                board[r][c] = d.toString()
                if(solveSudoku(board)) return true
                else board[r][c] = '.'
            }
        }
        return false
    }
};

var isValidSudoku = function(board, r, c, el){
    for(var i = 0; i < 9; i++){
        if(board[r][i] === el) return false
        if(board[i][c] === el) return false
    }
    for(var i = 3 * Math.floor(r/3); i < 3 * Math.floor(r/3) + 3; i++){
        for(var j = 3 * Math.floor(c/3); j < 3 * Math.floor(c/3) + 3; j++){
            if(board[i][j] === el) return false
        }
    }
    return true
}
var isEmpty = function(board){
    for(var i = 0; i < 9; i++){
        for(var j = 0; j < 9; j++){
            if(board[i][j] === '.') return [i, j]
        }
    }
    return [-1, -1]
}

你可能感兴趣的:(37)