判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
1.数字 1-9 在每一行只能出现一次。
2.数字 1-9 在每一列只能出现一次。
3.数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。
示例 1:
输入:
[
[“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
示例 2:
输入:
[
[“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 存在, 因此这个数独是无效的。
说明:
解法一:
效率不高
bool isValidSudoku(vector<vector<char>>& board) {
vector<vector<char>> vec(9);
vector<map<char,int>> vm(9);
char temp=0;
for(int i=0;i<9;++i)
{
map<char,int> m;
for(int j=0;j<9;++j)
{
temp=board[i][j];
vec[(i/3)*3+j/3].push_back(temp);
//对行判断
if(m.find(temp)==m.end())
{
if(temp!='.')
m[temp]=1;
}
else
return false;
//对列判断
if(vm[j].find(temp)==vm[j].end())
{
if(temp!='.')
vm[j][temp]=1;
}
else
return false;
}
}
//对9个小宫格判断
for(int i=0;i<9;++i)
{
map<char,int> m;
for(int j=0;j<9;++j)
{
temp=vec[i][j];
if(m.find(temp)==m.end())
{
if(temp!='.')
m[temp]=1;
}
else
return false;
}
}
return true;
}
解法二:
效率较高
static int xx = []() {
ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
std::vector<std::vector<bool>> row(9, vector<bool>(10, false));
std::vector<std::vector<bool>> col = row;
std::vector<std::vector<bool>> rect = row;
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
char c = board[i][j];
if (c == '.') continue;
int v = c - '0';
if (row[i][v] == true) return false;
if (col[j][v] == true) return false;
int n = i / 3 * 3 + j / 3;
if (rect[n][v] == true) return false;
row[i][v] = true;
col[j][v] = true;
rect[n][v] = true;
}
}
return true;
}