C++ Solution


  • 0
    S

    class Solution {
    public:

    bool IsValidNumber(vector<vector<char>> &board, int r, int c,char val ){
        
        /* Check rows for that column */ 
        int num_cols = board.size();
        int num_rows = num_cols;
    
        for (int i = 0; i < num_rows; ++i){
            if(board[i][c] == val){
                return false;
            }
        }
    
        for (int i = 0; i < num_cols;++i){
            if(board[r][i] == val){
                return false;
            }
        }
    
        int region_size = sqrt(num_cols);
        int I = r/region_size;
        int J = c/region_size;
        
        
        for (int i = 0; i < region_size; ++i){
            for (int j = 0; j < region_size; ++j){
                
                if(board[I*region_size+i][J*region_size+j] == val){
                    return false;
                }
            }
        }
    
        return true;
        
    }
    
    bool solveSudokuHelper(vector<vector<char>> &board, int i, int j)
    {
        if(j > board.size()){
            j = 0;
            if(++i == board.size()){
                return true;
            }
        }
        /* If that position is not empty */ 
        if(board[i][j] != '.'){
            return (solveSudokuHelper(board,i,j+1));
        }
        for (int n = 1; n <= board.size(); ++n){
       
            if(IsValidNumber(board,i,j,(char)('0' + n))){
                board[i][j] = (char)('0' + n);
                if(solveSudokuHelper(board,i,j+1)){
                    return true;
                }
                board[i][j] = '.';
            }
            
        }
        return false;
    }
    void solveSudoku(vector<vector<char>>& board) {
        bool r = solveSudokuHelper(board,0,0);
        return;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.