题目
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.
思路
本题本质上是验证数独,没啥取巧的方法,唯一就是遍历,二维数组的遍历。
但是根据数独特性,需要判断三种情况:
1.每一行没有重复数字出现,
2.每一列没有重复数字出现,
3.每个子九宫格没有重复数字出现
前两个很好判断,但是第三个如何判断第i个九宫格的第j个格子的行号与列号呢,这就是找规律了,总结如下:
第i个九宫格的第j个格点的行号可表示为i/3*3+j/3
第i个九宫格的第j个格点的列号可表示为i%3*3+j%3
代码
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
for(int i = 0; i < 9; i ++)
{
unordered_map<char, bool> m1; //check i_th row
unordered_map<char, bool> m2; //check i_th column
unordered_map<char, bool> m3; //check i_th subgrid
for(int j = 0; j < 9; j ++)
{
if(board[i][j] != '.')
{
if(m1[board[i][j]] == true)
return false;
m1[board[i][j]] = true;
}
if(board[j][i] != '.')
{
if(m2[board[j][i]] == true)
return false;
m2[board[j][i]] = true;
}
if(board[i/3*3+j/3][i%3*3+j%3] != '.')
{
if(m3[board[i/3*3+j/3][i%3*3+j%3]] == true)
return false;
m3[board[i/3*3+j/3][i%3*3+j%3]] = true;
}
}
}
return true;
}
};