36. Valid Sudoku

本文详细解析了如何通过三次遍历算法验证一个数独是否有效。利用vector记录每轮检查的状态,分别对行、列和九宫格进行检查,确保同一行、列或九宫格内没有重复的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

解答:

基本的三次遍历即可解决。使用一个vector记录是第几个round的记录。

代码:

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        vector<int> vec(10, -1);
        int round = 0;
        for(int i = 0;i < 9; ++i){
            for(int j = 0;j < 9; ++j){
                if(board[i][j] == '.')
                    continue;
                int index = board[i][j] - '0';
                if(vec[index] == round)
                    return false;
                else{
                    vec[index] = round;
                }
            }
            ++round;
        }
        
        for(int i = 0;i < 9; ++i){
            for(int j = 0;j < 9; ++j){
                if(board[j][i] == '.')
                    continue;
                int index = board[j][i] - '0';
                if(vec[index] == round)
                    return false;
                else{
                    vec[index] = round;
                }
            }
            ++round;
        }
        
        for(int i = 0;i < 9; i = i + 3)
            for(int j = 0;j < 9; j = j + 3){
                for(int k = i;k < i + 3; ++k)
                    for(int l = j;l < j + 3; ++l){
                        if(board[k][l] == '.')
                            continue;
                        int index = board[k][l]-'0';
                        if(vec[index] == round)
                            return false;
                        else{
                            vec[index] = round;
                        }
                    }
                ++round;
            }
        return true;
    }
};

更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值