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.
这道题是判断部分填充好的数独是否正确,不考虑没有填充的部分,题目难度为easy。
不熟悉数独游戏的同学请问度娘,这里不再详细介绍规则。题目没有要求找出结果,第37题会给出求解的过程。这里只需要判断每行、每列、每个小的九宫格中是否有重复的数字即可,很自然会选用Hash Table来存储已经出现过的数字。具体代码:
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
vector<unordered_set<char>> rows(9), cols(9), grid(9);
for(int i=0; i<9; ++i) {
for(int j=0; j<9; ++j) {
if(board[i][j] == '.') continue;
if(rows[i].find(board[i][j]) != rows[i].end()) return false;
else rows[i].insert(board[i][j]);
if(cols[j].find(board[i][j]) != cols[j].end()) return false;
else cols[j].insert(board[i][j]);
int n = i - i%3 + j/3;
if(grid[n].find(board[i][j]) != grid[n].end()) return false;
else grid[n].insert(board[i][j]);
}
}
return true;
}
};