leetcode36 - Valid Sudoku

题目:
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:

A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.
大概需要满足一下要求:
每行必须包含数字1-9,且不能重复。
每列必须包含数字1-9,不能重复。
网格的9个3 x 3子框中的每个必须包含数字1-9(无重复)。
只需要把他们分开判断就行了。(因为正好在复习C++模板部分,就在里面尝试着使用了一下)

class Solution {
public:
    template <typename T>
    bool isRight(vector<T> &arr){
        for(auto i : arr){
            if(i > 1)return false;
        }
        return true;
    }
    
    template <typename T>
    bool check_Row_And_Col(vector<vector<T>>& board){
        for(auto i = 0; i < board.size(); i++){
            vector<T>row(10, 0);
            vector<T>col(10, 0);
            for(auto j = 0; j < board.size(); j++)
            {
                if(board[i][j]!='.'){
                    auto temp = board[i][j] - '0';
                    row[temp]++;
                }
                if(board[j][i]!='.'){
                    auto temp = board[j][i] - '0';
                    col[temp]++;
                }
            }
            if(!isRight(row) or !isRight(col))return false;
        }
        return true;
    }
    
    template <typename T>
    bool cheak_box(vector<vector<T>>& board){
        for(auto i=0; i<board.size(); i += 3)
            for(auto j = 0; j < board.size(); j += 3){
                vector<T>box(10, 0);
                for(auto m = 0; m < 3; m++)
                    for(auto n = 0; n < 3; n++)
                        if(board[i+m][j+n] != '.'){
                            auto temp = board[i+m][j+n] - '0';
                            box[temp]++;
                        }
                if(!isRight(box))return false;
                        
            }
        return true;
    }
    bool isValidSudoku(vector<vector<char>>& board) {
         if(check_Row_And_Col(board) and cheak_box(board))
             return true;
        else return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值