My C++ Solution 15ms


  • 0

    Three vectors are used to store the number appeared.

    hvec: to store each row's number

    vvec: to store each column's number

    svec: to store each sub-boxes' number

    class Solution
    {
    private:
        const int N = 9;
    public:
        bool isValidSudoku(vector<vector<char>>& board)
        {
            if(board.size( ) != N&&board[0].size()!=N) { return false; }
            vector<string>  hvec(N), vvec(N), svec(N);
            for(auto i = 0; i != N; ++i)
            {
                for(auto j = 0; j != N; ++j)
                {
                    if(board[i][j] == '.') continue;
                    
                    char c = board[i][j];
                    if(hvec[i].find(c) == string::npos)
                    {
                        hvec[i].push_back(c);
                    }
                    else
                    {
                        return false;
                    }
    
                    if(vvec[j].find(c) == string::npos)
                    {
                        vvec[j].push_back(c);
                    }
                    else
                    {
                        return false;
                    }
    
                    if(svec[( i / 3 ) * 3 +j / 3].find(c) == string::npos)
                    {
                        svec[( i / 3 ) * 3 +  j / 3].push_back(c);
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            return true;
        }
    };
    

Log in to reply
 

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