c++ 16ms simple solution using O(n) space


  • 0
    class Solution {
    public:
        bool isValidSudoku(vector<vector<char>>& board) {
            //judge each col
            for(int i=0; i<9; i++)
            {
                set<char> s;
                for(int j=0; j<9; j++)
                {
                    char c = board[i][j];
                    if(c != '.')
                    {
                        if(s.find(c)!=s.end())
                            return false;
                        else
                            s.insert(c);
                    }
                }
            }
            //judge each row
            for(int j=0; j<9; j++)
            {
                set<char> s;
                for(int i=0; i<9; i++)
                {
                    char c = board[i][j];
                    if(c != '.')
                    {
                        if(s.find(c)!=s.end())
                            return false;
                        else
                            s.insert(c);
                    }
                }
            }
            //judge each block
            for(int i=0; i<9; i+=3)
            {
                for(int j=0; j<9; j+=3)
                {
                    set<char> s;
                    for(int m=0; m<3; m++)
                    {
                        for(int n=0; n<3; n++)
                        {
                            char c = board[i+m][j+n];
                            if(c != '.')
                            {
                                if(s.find(c)!=s.end())
                                    return false;
                                else
                                    s.insert(c);
                            }   
                        }
                    }
                }
            }
            return true;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.