用于检查我们是否有有效数独的辅助功能

Helper function for checking if we have a valid sudoku

本文关键字:功能 有效数 检查 我们 是否 用于      更新时间:2023-10-16

我正在关注一本名为《编程访谈元素》的书,我正在阅读第 79 页上一个名为HasDuplicate的辅助函数,但我很难理解它是如何工作的。

这是代码:

// Return true if subarray partial_assignment[start_row]
// [end_row -  1][start_col, end_col - 1] contains any duplicate
// in {1, 2 ..., size(partial_assignemnt)}; otherwise return false.
bool HasDuplicate(const vector<vector<int>>& partial_assignment, int start_row, int end_row, int start_col, int end_col)
{
deque<bool> is_present(size(partial_assignment) + 1, false);
for(int i = start_row; i < end_row; ++i)
{
for(int j = start_col; j < end_col; ++j)
{
if(partial_assignment[i][j] != 0 && is_present[partial_assignment[i][j]])
return true;
is_present[partial_assignment[i][j]] = true;
}
}
return false;
}

请注意,partial_assignment是部分填充的数独网格。我只是不确定它如何检查是否有重复项。也许它与德克有关?

代码中的注释:

bool HasDuplicate(const vector<vector<int>>& partial_assignment, int start_row, 
int end_row, int start_col, int end_col)
{
// this creates a container for bookkeeping of used numbers
// size+1 because the number 1-x are used.
deque<bool> is_present(size(partial_assignment) + 1, false);
// The variables i and j are used to go through every coordinate on the
// sudoku game board.
for(int i = start_row; i < end_row; ++i)
{
for(int j = start_col; j < end_col; ++j)
{
// here it checks if the current number is already marked as used in "is_present"
// if it is, then it's a duplicate and the function returns true.
// The value 0 is used at coordinates where no number has been
// selected.
if(partial_assignment[i][j] != 0 && is_present[partial_assignment[i][j]])
return true;
// otherwise, mark the number as used
is_present[partial_assignment[i][j]] = true;
}
}
return false;
}