Topic links: https://leetcode-cn.com/problems/valid-sudoku/
Title Description
Determining a number of unique 9x9 is valid. Only according to the following rules, to verify whether the numbers already filled can be effective.
- The numbers 1-9 appear only once in each row.
- The numbers 1-9 appear only once in each column.
- Figures 1-9 only appear once in each 3x3 intrauterine separated by a thick solid line.
The figure is the number of valid only a partially filled.
Sudoku part of this space has been filled in the numbers, empty cells with '.' Representation.
Example 1:
输入:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
输出: true
Example 2:
输入:
[
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
输出: false
解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。
但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
Description:
- Only a valid number (portion has been filled) is not necessarily solvable.
- According to the above rules only need to verify whether the figures have been filled can be effective.
- Given the number of unique sequence comprises only numeric characters 1-9 and '.'.
- Sudoku will always be given in the form of 9x9.
Thinking
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_set<char> s;
// 检查每一行
for (int i = 0; i < board.size(); ++i) {
s.clear();
for (int j = 0; j < board[0].size(); ++j) {
if(board[i][j] != '.'){
if(s.count(board[i][j]) == 0)
s.insert(board[i][j]);
else
return false;
}
}
}
// 检查每一列
for (int j = 0; j < board[0].size(); ++j) {
s.clear();
for (int i = 0; i < board.size(); ++i) {
if(board[i][j] != '.'){
if(s.count(board[i][j]) == 0)
s.insert(board[i][j]);
else
return false;
}
}
}
// 检查每个九宫格
for (int k = 0; k < 9; ++k) {
int x = k /3 * 3, y = (k %3) * 3;
s.clear();
for (int i = x; i < x+3; ++i) {
for (int j = y; j < y+3; ++j) {
if(board[i][j] != '.'){
if(s.count(board[i][j]) == 0)
s.insert(board[i][j]);
else
return false;
}
}
}
}
return true;
}
};