9.Valid Sudoku

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.

  2. Each column must contain the digits 1-9 without repetition.

  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Solution : Using Hashset

class Solution
{
public:
    bool columnValid(vector<vector<char>> &v)
    {
        for (int i = 0; i < v.size(); i++)
        {
            unordered_set<char> s;
            for (int j = 0; j < v[i].size(); j++)
            {
                if (v[i][j] == '.')
                {
                    continue;
                }

                if (s.find(v[i][j]) != s.end())
                {
                    return false;
                }
                else
                {
                    s.insert(v[i][j]);
                }
            }
        }
        return true;
    }

    bool rowValid(vector<vector<char>> &v)
    {
        for (int i = 0; i < v.size(); i++)
        {
            unordered_set<char> s;
            for (int j = 0; j < v[i].size(); j++)
            {
                if (v[j][i] == '.')
                {
                    continue;
                }

                if (s.find(v[j][i]) != s.end())
                {
                    return false;
                }
                else
                {
                    s.insert(v[j][i]);
                }
            }
        }
        return true;
    }

    bool gridValid(vector<vector<char>> &v, int row, int col)
    {
        unordered_set<int> s;

        for (int i = row; i < row+3; i++)
        {
            for (int j = col; j < col+3; j++)
            {
                if (v[i][j] == '.')
                {
                    continue;
                }

                if (s.find(v[i][j]) != s.end())
                {
                    return false;
                }
                else
                {
                    s.insert(v[i][j]);
                }
            }
        }
        return true;
    }

    bool isValidSudoku(vector<vector<char>> &board)
    {
        if (rowValid(board) && columnValid(board))
        {
            for (int i = 0; i < 9; i += 3)
            {
                for (int j = 0; j < 9; j += 3)
                {
                    if (!gridValid(board, i, j))
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        return false;
    }
};

Last updated