题目要求:
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.
这道题解法暂没有比较巧妙的,所以下边程序所用方法就是Brute Force(暴力破解):
class Solution {
public:
int charToInt(char c)
{
char str[] = {'', '', '', '', '', '', '', '', ''};
int intStr[] = {, , , , , , , , };
for(int i = ; i < ; i++)
{
if(c == str[i])
return intStr[i];
}
return -;
} bool isValidSudoku(vector<vector<char>>& board) {
unordered_map<int, int> hashMap;
for(int i = ; i < ; i++)
hashMap[i] = ;
// row by row
for(int i = ; i < ; i++)
{
for(int k = ; k < ; k++)
hashMap[k] = ;
for(int j = ; j < ; j++)
{
int tmp = charToInt(board[i][j]);
if(tmp != -)
{
hashMap[tmp]++;
if(hashMap[tmp] > )
return false;
}
}
}
// column by column
for(int j = ; j < ; j++)
{
for(int k = ; k < ; k++)
hashMap[k] = ;
for(int i = ; i < ; i++)
{
int tmp = charToInt(board[i][j]);
if(tmp != -)
{
hashMap[tmp]++;
if(hashMap[tmp] > )
return false;
}
}
}
// 3*3 boxes by 3*3 boxes
for(int i = ; i < ; i += )
{
for(int j = ; j < ; j += )
{
for(int k = ; k < ; k++)
hashMap[k] = ;
for(int m = i; m < i + ; m++)
for(int n = j; n < j + ; n++)
{
int tmp = charToInt(board[m][n]);
if(tmp != -)
{
hashMap[tmp]++;
if(hashMap[tmp] > )
return false;
}
}
}
} return true;
}
};