leetcode 36. Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.


A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.



class Solution {
public:
	bool isValidSudoku(vector<vector<char>>& board) {
		char aa[9] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		set <char>nums(aa, aa + 9);
		for (int i = 0; i < board.size(); i++)
		{
			set<char>bb = nums;
			for (int j = 0; j < board[0].size(); j++)
				if (board[i][j] != '.')
				{
				set<char>::iterator it = bb.find(board[i][j]);
				if (it == bb.end())
					return false;
				bb.erase(it);
				}
		}
		for (int i = 0; i < board[0].size(); i++)
		{
			set<char>bb = nums;
			for (int j = 0; j < board.size(); j++)
				if (board[j][i] != '.')
				{
				set<char>::iterator it = bb.find(board[j][i]);
				if (it == bb.end())
					return false;
				bb.erase(it);
				}
		}
		for (int i = 0; i < board.size(); i += 3)
		{
			for (int j = 0; j < board[0].size(); j += 3)
			{
				set<char>bb = nums;
				for (int y = 0; y < 3; y++)
					for (int x = 0; x < 3; x++)
						if (board[i + y][j + x] != '.')
						{
					set<char>::iterator it = bb.find(board[i + y][j + x]);
					if (it == bb.end())
						return false;
					bb.erase(it);
						}

			}
		}
		return true;
	}
};

accept


你可能感兴趣的:(LeetCode)