c++ - 用于检查我们是否拥有有效数独的辅助函数

标签 c++

我正在阅读一本名为 Elements of Programming Interviews 的书,并且正在阅读第 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;
}

关于c++ - 用于检查我们是否拥有有效数独的辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58497506/

相关文章:

c++ - 运算符>> 用 C++ 映射重载

C++延迟任务

c++ - 从多重继承继承

c++ - 无穷大与 NAN 值

c++ - 使用类型和非类型参数在模板类外部定义函数

c++ - 标准运算符的函数指针

c++ - 使用列表的此 C++ 代码出现段错误的原因是什么?

c++ - 将 int(或 long,或其他)截断为特定大小(n 字节),有符号和无符号

c++ - Protocol Buffer 问题,多个序列化为二进制文件

c++ - 食人魔 3d : RenderTexture bigger than RenderWindow