leetcode相关C++算法解答: https://github.com/Nereus-Minos/C_plus_plus-leetcode
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
输入:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
输出: true
输入:
[
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
输出: false
解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
分别写三个验证函数,行验证,列验证,3*3验证
使用三个存放map的vecotr来一次遍历
#if 0
//方法一:分别写三个验证函数,行验证,列验证,3*3验证
#if 0
//方法一:分别写三个验证函数,行验证,列验证,3*3验证
class Solution {
public:
bool isValidSudoku(vector>& board) {
//写三个函数分别验证
return rowIsValid(board) && colIsValid(board) && threeIsValid(board);
}
private:
bool rowIsValid(vector>& board){
for(int i = 0; i < 9; i++)
{
map temp;
for(int j = 0; j < 9; j++)
{
if(board[i][j] != '.')
{
if(temp.find(board[i][j]) != temp.end())
return false;
else
temp[board[i][j]] = 1;
}
}
}
return true;
}
bool colIsValid(vector>& board){
for(int i = 0; i < 9; i++)
{
map temp;
for(int j = 0; j < 9; j++)
{
if(board[j][i] != '.')
{
if(temp.find(board[j][i]) != temp.end())
return false;
else
temp[board[j][i]] = 1;
}
}
}
return true;
}
bool threeIsValid(vector>& board){
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
map temp;
for(int k = 0; k < 9; k++)
{
if(board[i*3+(k/3)][j*3+(k%3)] != '.')
{
if(temp.find(board[i*3+(k/3)][j*3+(k%3)]) != temp.end())
return false;
else
temp[board[i*3+(k/3)][j*3+(k%3)]] = 1;
}
}
}
}
return true;
}
};
#endif
#if 1
//方法二:使用三个存放map的vecotr来一次遍历
class Solution {
public:
bool isValidSudoku(vector>& board) {
vector