我正在尝试做一个在线数独C++测试题。
我需要确定9x9数独板是否有效。只有已填充的单元格需要根据以下规则进行验证(某些单元格有“.”表示未填充):
-
每行必须包含数字1-9,不得重复。
-
每列必须包含数字1-9,不得重复。
-
网格的9个3x3子框中的每个子框必须包含数字1-9,不能重复。
对于我的解决方案,我将遍历每一行、每一列和每一个子框网格。把这些数字加到地图上。并检查地图是否有任何副本。
我很确定我有标准
1
和
2
解决了,但我无法想象如何循环通过子框3x3网格。所以我适应了
some code found here
说实话,我还是不能完全清醒。我认为那部分可能是造成问题的原因。
如何解决标准3?
示例输入,正确的答案应返回假,但我的代码返回真:
[
[".",".","4",".",".",".","6","3","."],
[".",".",".",".",".",".",".",".","."],
["5",".",".",".",".",".",".","9","."],
[".",".",".","5","6",".",".",".","."],
["4",".","3",".",".",".",".",".","1"],
[".",".",".","7",".",".",".",".","."],
[".",".",".","5",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."]
]
我的(坏的)解决方案:
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
//Iterate over each row
for (int x = 0; x < 9; x++) {
//Add row numbers to map
map<char, int> row_nums {};
for (int i = 0; i < 9; i++) {
if (board[x][i] != '.') {
row_nums[board[x][i]]++;
}
}
//Return false if duplicates found in row map
for (auto it = row_nums.begin(); it != row_nums.end(); ++it) {
if (it->second > 1) {
return false;
}
}
}
//Iterate over columns
for (int i = 0; i < 9; i++) {
//Add column numbers to map
map<char, int> col_nums {};
for (int y = 0; y < 9; y++) {
if (board[i][y] != '.') {
col_nums[board[i][y]]++;
}
}
//Return false if duplicates found in column map
for (auto it = col_nums.begin(); it != col_nums.end(); it++) {
if (it->second > 1) {
return false;
}
}
}
//Iterate over the 3x3 sub-boxes and add numbers to a map
//I think this is where I am stuck
for (int x = 0; x < 9; x++) {
for (int y = 0; y < 9; y++) {
map<char, int> box_nums {};
for (int bx = (x/3)*3; bx < (x/3)*3 + 3; bx++) {
for (int by = (y/3)*3; by < (y/3)*3 + 3; by++) {
if (board[bx][by] != '.') {
box_nums[board[bx][by]]++;
}
}
}
//Return false if duplicates found in column map
for (auto it = box_nums.begin(); it != box_nums.end(); it++) {
if (it->second > 1) {
return false;
}
}
}
}
//Else return true
return true;
}
};