leetcode #36 in cpp.

The question is to determine a Sudoku is valid. 

Solution:  if a Sudoku is valid, each row, each column and each block in it would not have duplicates.Thus we have 3 loops to check if each condition is satisfied. We can use hashmap to check if there are duplicates.

I find out using loops to check each block using a hash map of size 9 is quite frustrating. And I don't want to use 9 hash maps for 9 blocks. Thus I write a recurrence function to check the block. Each recurrent call check one block.  

Code: 

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        if(board.empty()) return 0;
        return check_row(board) && check_col(board) && check_block(board,0,0,0);
    }
    bool check_row(vector<vector<char>> board){
        for(int row = 0; row < board.size(); row++){
            map<char,int> mapp;
            for(int col = 0; col < board[0].size(); col ++){
                if(board[row][col] == '.') continue;
                if(mapp.find(board[row][col]) != mapp.end()) return 0;
                else mapp[board[row][col]] = 1;
            }
        }
        return 1;
        
    }
    bool check_col(vector<vector<char>> board){
        for(int col = 0; col < board[0].size(); col++){
            map<char,int> mapp;
            for(int row = 0; row < board.size(); row ++){
                if(board[row][col] == '.') continue;
                if(mapp.find(board[row][col]) != mapp.end()) return 0;
                else mapp[board[row][col]] = 1;
            }
        }
        return 1;
        
    }
    bool check_block(vector<vector<char>> board,int start_row, int start_col,int count){
        if(count == 9) return 1;
        int row_upper = start_row + 3;//range of current block
        int col_upper = start_col + 3;//range of current block
        int row = start_row;
        int col = start_col;
        map<char, int> mapp;
        //check current block
        for(; row < row_upper; row++){
            for(;col < col_upper; col++){
                if(board[row][col] == '.') continue;
                if(mapp.find(board[row][col])!=mapp.end()) return 0; 
                mapp[board[row][col]] = 1;
            }
            col = start_col;//get to the next row and initial column
        }
        if(col_upper == 9){//the next block will start at the next row+3 with col = 0
            start_col = 0;
            start_row += 3;
        }else{//next block is still in the same rows but with different start_col
            start_col = col_upper;
        }
        return check_block(board, start_row, start_col, count + 1);
        
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值