Loading

【leetcode】36. Valid Sudoku(判断能否是合法的数独puzzle)

  Share Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules.

  分别建立三个hash_set 注意这是建立个hash_set数组 【】,而不是单单建立一个hash表。

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int n=9;// 题目中给的是9x9 的sudoku puzzle
        unordered_set<char> row[n]; //这是创建hash数组 之前没这么用过
        unordered_set<char> cloumn[n];
        unordered_set<char> square[n];
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                int sr=i/3;
                int sc=j/3;
                int sq=sr*3+sc;
                char tmp=board[i][j];
                if(tmp=='.') continue;
                if(row[i].count(tmp)>0 || cloumn[j].count(tmp)>0 || square[sq].count(tmp)>0)
                {
                    return false;
                }
                row[i].insert(tmp);
                cloumn[j].insert(tmp);
                square[sq].insert(tmp);
                    
            }
        }
        return true;

    }
};

 

 

posted @ 2021-11-19 21:03  aalanwyr  阅读(42)  评论(0编辑  收藏  举报