Valid sudoku using unordered_set


  • 0
    P
    class Solution {
    public:
        bool isValidSudoku(vector<vector<char>>& board) {
            return (isValidLinesSudoku(board) && isValidColumnsSudoku(board) && isValidSquaresSudoku(board));
        }
    
        bool isValidSquaresSudoku(vector< vector<char> >& board)
        {
        	int nbTiles = 3;
        	int sizeTile = 3;
        	int y, x;
        
        	for(int rt = 0; rt < nbTiles; rt++)
        	{
        		for(int ct = 0; ct < nbTiles; ct++)
        		{
        			unordered_set<char> charSet;
        			for(int r = 0; r < sizeTile; r++)
        			{
        				for(int c = 0; c < sizeTile; c++)
        				{
        					y = rt*sizeTile + r;
        					x = ct*sizeTile + c;
        					if(board[y][x] != '.')
        					{
        						auto isHere = charSet.find(board[y][x]);
        						if(isHere != charSet.end())
        							return false;
        						else
        							charSet.insert(board[y][x]);
        					}
        				}
        			}
        		}
        	}
        	return true;
        }
    
        bool isValidColumnsSudoku(vector< vector<char> >& board)
        {
        	for(int c = 0; c < board[0].size(); c++)
        	{
        		unordered_set<char> charSet;
        		for(int r = 0; r < board.size(); r++)
        		{
        			if(board[r][c] != '.')
        			{
        				auto isHere = charSet.find(board[r][c]);
        				if(isHere != charSet.end())
        					return false;
        				else
        					charSet.insert(board[r][c]);
        			}
        		}
        	}
        	return true;
        }
    
        bool isValidLinesSudoku(vector< vector<char> >& board)
        {
        	for(int r = 0; r < board.size(); r++)
        	{
        		unordered_set<char> charSet;
        		for(auto& c : board[r])
        		{
        			if(c != '.')
        			{
        				auto isHere = charSet.find(c);
        				if(isHere != charSet.end())
        					return false;
        				else
        					charSet.insert(c);
        			}
        		}
        	}
        	return true;
        }
    };

Log in to reply
 

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