problem:
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 '.'
.
该问题是判断该数独盘是否合理,不用考虑最后能不能求解。
考虑3个方便。第一是每行没有数字重复,第二是每列没有数字重复,第三是每个3*3的方框里面无数字重复。
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
if (board.empty())
return false;
int size = board.size();
vector<int> count;
//考虑每行
for (int i = 0; i < size; ++i)
{
count.assign(9, 0);
for (int j = 0; j < size; j++)
{
if (board[i][j] != '.')
{
int pos = board[i][j] - '1';
if (count[pos] > 0)
return false;
else
++count[pos];
}
continue;
}
}
//考虑每列
for (int j = 0; j < size; ++j)
{
count.assign(9, 0);
for (int i = 0; i < size; i++)
{
if (board[i][j] != '.')
{
int pos = board[i][j] - '1';
if (count[pos] > 0)
return false;
else
++count[pos];
}
continue;
}
}
//考虑每3*3的方块内
for (int i = 0; i < size; i += 3)
{
for (int j = 0; j < size; j += 3)
{
count.assign(9, 0);
for (int row = i; row < i + 3;row++)
for (int col = j; col < j + 3; col++)
{
if (board[row][col] != '.')
{
int pos = board[row][col] - '1';
if (count[pos] > 0)
return false;
else
++count[pos];;
}
else
continue;
}
}
}
return true;
}
};