[leetcode] 36. Valid Sudoku

本文介绍了一种验证数独是否有效的方法,通过使用三个布尔型矩阵来跟踪每一行、每一列及每个3x3宫格内数字的出现情况。文章详细解释了如何利用这些矩阵进行有效性检查,并附带了一个具体的C++实现示例。

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.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

解法一:

数独的规则就是行、列、9个3*3的cell中不能出现重复的数字。思路是创建三个矩阵,row, col, cell, row[i][c]表示第i行中出现了数字c, col[j][c] 表示第j列出现了数字c, cell[k][c]表示第k个cell出现了数字c。每次去检查 row, col, cell中对应元素是不是有一个为true。

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        // check size
        if (board.size()!=9) return false;
        //////
        vector<vector<bool> > row_flag(9,vector<bool>(9,false));
        vector<vector<bool> > col_flag(9,vector<bool>(9,false));
        vector<vector<bool> > cell_flag(9,vector<bool>(9,false));
        
        for(int i=0; i<9; i++){
            if (board[i].size()!=9)
                return false;
            for (int j=0; j<9; j++){
                if (!validFill(board[i][j]))
                    return false;
                if (board[i][j] >= '1' && board[i][j] <= '9'){
                    int val = board[i][j] - '1';
                    if (row_flag[i][val] || col_flag[j][val] || cell_flag[3*(i/3)+j/3][val]) return false;
                    row_flag[i][val] = true;
                    col_flag[j][val] = true;
                    cell_flag[3*(i/3)+j/3][val] = true;
                }
                
            }
        
        }
        
        return true;
        
    }
    
    bool validFill(char c){
        return c == '1' || c == '2' || c == '3' || c == '4' || c == '5' ||
                c == '6' || c == '7' || c == '8' || c == '9' || c == '.';
    }
};







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值