Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 理解8皇后拼图的对角搜索_C++_C_Algorithm_Search - Fatal编程技术网

C++ 理解8皇后拼图的对角搜索

C++ 理解8皇后拼图的对角搜索,c++,c,algorithm,search,C++,C,Algorithm,Search,我正在解决这个问题,并试图通过互联网寻找比较解决方案,看看我的解决方案与其他解决方案相比如何。我发现了一个非常小的暴力解决方案,这让我很困惑。我想知道是否有人愿意解释对角线比较是如何工作的 void solve(int n, int col, int *hist) { int i; int j; if (col == n) { print_solution(n, hist); } i = 0; while (i <

我正在解决这个问题,并试图通过互联网寻找比较解决方案,看看我的解决方案与其他解决方案相比如何。我发现了一个非常小的暴力解决方案,这让我很困惑。我想知道是否有人愿意解释对角线比较是如何工作的

void solve(int n, int col, int *hist)
{
    int i;
    int j;

    if (col == n)
    {
        print_solution(n, hist);
    }
    i = 0;
    while (i < n)
    {
        j = 0;
        while (j < col && !(hist[j] == i || abs(hist[j] - i) == col - j))
            j++;
        if (j < col)
        {
            i++;
            continue;
        }
        hist[col] = i;
        solve(n, col + 1, hist);
        i++;
    }
}

void main(void)
{
    int hist[8];

    solve(8, 0, hist);
}

据我所知,它检查对角线,但我看不到。

由于第一个循环条件是
j
,因此该条件的右侧为正值
i
对应于正在检查的当前行,
hist[j]
j
-th列上女王的行。因此,通过检查水平距离和垂直距离是否相等,检查两点
(hist[j],j)
(i,col)
是否位于对角线上的“正斜杠”(/)或“反斜杠”(\)。
abs
允许一次检查两个案例。

用笔和纸手动检查。(这就是我要向你解释的,所以你也可以这么做。)@meowgoes狗从main经过。int hist[8]例如,历史缓冲区。@PaulOgilvie我试过了,但数字对我来说没有意义。
abs(hist[j] - i) == col - j)