leetcode刷题,总结,记录,备忘 36

leetcode36Valid Sudoku

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.

Subscribe to see which companies asked this question

分别划定3个包含9个set的数组,为9行9列和9个9宫格,然后利用set的特性,不允许重复的元素,进行插入元素判断是否为有效的数独即可,使用i/3*3 + j/3这个公式来判断第i行和第j列的元素属于第几个9宫格,还是很简单的。详情看代码

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        vector<set<char> > vsr(9, set<char>());
        vector<set<char> > vsc(9, set<char>());
        vector<set<char> > vsm(9, set<char>());
        
        for (int i = 0; i < board.size(); ++i)
        {
            for (int j = 0; j < board[i].size(); ++j)
            {
                char val = board[i][j];
                if (val == '.')
                {
                    continue;
                }
                else
                {
                    pair<set<char>::iterator, bool> br = vsr[i].insert(val);
                    pair<set<char>::iterator, bool> bc = vsc[j].insert(val);
                    pair<set<char>::iterator, bool> bm = vsm[i/3*3 + j/3].insert(val);
                    
                    if (!br.second || !bc.second || !bm.second)
                    {
                        return false;
                    }
                }
            }
        }
        
        return true;
        
    }
};


你可能感兴趣的:(leetcode刷题,总结,记录,备忘 36)