LeetCode 36. Valid Sudoku (C++)

本文介绍了一种使用C++实现的数独有效性验证算法。通过遍历数独矩阵,检查每一行、每一列以及每个3x3子网格是否包含重复的1-9数字,从而判断数独是否有效。算法采用map数据结构存储已出现的数字,避免了重复计数。

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

题目:

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

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

分析:

每一行,每一列没有相同的数字,每一个3*3的小正方形中也没有相同的数字。可以使用数组,map,set等等来判断。

程序:

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        map<char,int> m;
        for (int i = 0; i < 9; i++){
            for (int j = 0; j < 9; j++){
                if (board[i][j] != '.'){
                    if (m[board[i][j]]) return false;
                    m[board[i][j]]++;
                }
            }
            m.clear();
        }
        for (int i = 0; i < 9; i++){
            for (int j = 0; j < 9; j++){
                if (board[j][i] != '.'){
                    if (m[board[j][i]]) return false;
                    m[board[j][i]]++;
                }
            }
             m.clear();
        }
        for (int i = 0; i < 3; i++){
            for (int j = 0; j < 3; j++){
                for (int r = i*3; r < i*3+3; r++){
                    for (int l = j*3; l < j*3+3; l++){
                        if (board[r][l] != '.'){
                            if (m[board[r][l]]) return false;
                            m[board[r][l]]++;
                        }
                    }
                }
                m.clear();
            }
        }
        return true;
    }
};

转载于:https://www.cnblogs.com/silentteller/p/10184697.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值