32 - Valid Sudoku

本文介绍了一种通过记录行、列及区块内数字出现次数的方法来判断数独是否有效。利用多个二维数组跟踪1到9这些数字在数独中的分布情况,确保每个数字在同一行、同一列和同一区块内不重复出现。

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

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.


A partially filled sudoku which is valid.



solution:空间换时间,设置多个二维数组分别记录横,纵,块中九个数字的出现次数,若重复出现则报错,反之该数独是valid的。

PS: 还需要判断数是否在1-9之间,若超出该范围也是错误的。


class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int si = board[0].size();
        if(si <= 0)
            return false;
        
        vector< vector<bool> >rows(si,vector<bool>(si,false));
        vector< vector<bool> >cols(si,vector<bool>(si,false));
        vector< vector<bool> >blocks(si,vector<bool>(si,false));
        
        for(int row = 0; row < si; row++)
        {
            for(int col = 0; col < si; col++)
            {
                char temp = board[ row ][ col ];
                if(temp == '.')
                    continue;
                int num = temp - '1';
                if( rows[ row ][ num ] || cols[ col ][ num ] || blocks[ col/3 + row - row % 3 ][ num ] )
                    return false;
                
                rows[ row ][ num ] = true;
                cols[ col ][ num ] = true;
                blocks[ col/3 + row - row % 3 ][ num ] = true;
            }
        }
        return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值