题目:
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.
思路:暴力搜索就能AC。
- 建立一个map,计数,把每个数字映射到相应的map里。
- 检查每行。
- 检查每列。
- 检查3×3的patch。
C++代码:
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
if (board.empty())
return false;
int sz = board.size();
vector<int> map;
//check rows
for (int i = 0; i < sz; i++)
{
map.assign(sz, 0);
for (int j = 0; j < sz; j++)
{
if (board[i][j] != '.')
{
int pos = board[i][j] - '1';
if (map[pos] > 0)
return false;
else
++map[pos];
}
else
continue;
}
}
//check columns
for (int j = 0; j < sz; j++)
{
map.assign(sz, 0);
for (int i = 0; i < sz; i++)
{
if (board[i][j] != '.')
{
int pos = board[i][j] - '1';
if (map[pos] > 0)
return false;
else
++map[pos];
}
else
continue;
}
}
//check 3*3 patches
for (int i = 0; i < sz; i += 3)
{
for (int j = 0; j < sz; j += 3)
{
map.assign(sz, 0);
for (int m = i; m < i + 3; m++)
{
for (int n = j; n < j + 3; n++)
{
if (board[m][n] != '.')
{
int pos = board[m][n] - '1';
if (map[pos] > 0)
return false;
else
++map[pos];
}
else
continue;
}
}
}
}
return true;
}
};