Loading

36. 有效的数独

题目

 

代码

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        //判断9宫格
        for(int i=1;i<8;i+=3)
        {
            for(int j=1;j<8;j+=3)
            {
                std::map<char,int> table;
                table[ board[i-1][j-1]]++;
                table[ board[i-1][j]]++;
                table[ board[i-1][j+1]]++;
                table[ board[i][j-1]]++;
                table[ board[i][j]]++;
                table[ board[i][j+1]]++;
                table[ board[i+1][j-1]]++;
                table[ board[i+1][j]]++;
                table[ board[i+1][j+1]]++;
                for(auto i:table)
                {
                    if(i.first!='.'&&i.second>1)
                        return false;
                }
            }
        }
        //判断水平
        
    
        for(int i=0;i<board.size();i++)
        {
            std::map<char,int> hori;
            for(int j=0;j<board[0].size();j++)
            {
                 hori[board[i][j]]++;
            }
            for(auto i:hori)
            {
                if(i.first!='.'&&i.second>1)
                    return false;
            }
           
        }
        //判断竖直
        for(int j=0;j<board.size();j++)
        {
               std::map<char,int> verti;
            for(int i=0;i<board[0].size();i++)
            {
                 verti[board[i][j]]++;
            }
            for(auto temp:verti)
            {
                if(temp.first!='.'&&temp.second>1)
                    return false;
            }
           
        }
        return true;
    }
};

 

思路

暴力破解法,直接按照规则判断九宫格和每个横线和竖线上的数字是否符合规则。时间复杂度为O(n²)

posted @ 2018-09-13 15:37  李正浩  阅读(129)  评论(0编辑  收藏  举报