题目:
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解:
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board)
{
bool used[10];
//检查行
for (int i = 0; i < 9; i++)
{
fill(used,used + 10,false);
for (int j = 0; j < 9; j++)
{
if (!check(used,board[i][j]))
return false;
}
}
//检查列
for (int i = 0; i < 9; i++)
{
fill(used,used + 10,false);
for (int j = 0; j < 9; j++)
if (!check(used,board[j][i]))
return false;
}
//检查九方格
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
fill(used,used + 10,false);
for (int m = 3 * i; m < 3 * i + 3; m++)
for (int n = 3 * j; n < 3 * j + 3; n++)
if (!check(used,board[m][n]))
return false;
}
return true;
}
bool check(bool used [],char a)
{
if (a == '.') return true;
if (used[a - '0']) return false;
used[a - '0'] = true;
return true;
}
};

本文介绍了一种简单有效的算法来验证数独是否有效。通过检查数独的每一行、每一列以及每一个九宫格内的数字是否重复,可以快速判断一个数独是否符合基本规则。
506

被折叠的 条评论
为什么被折叠?



