【问题标题】:Recursion differences in backtracking with a global value?与全局值回溯的递归差异?
【发布时间】:2014-03-30 04:06:55
【问题描述】:

this为例:

bool SolveSudoku(int grid[N][N])
{
    int row, col;
 
    // If there is no unassigned location, we are done
    if (!FindUnassignedLocation(grid, row, col))
       return true; // success!
 
    // consider digits 1 to 9
    for (int num = 1; num <= 9; num++)
    {
        // if looks promising
        if (isSafe(grid, row, col, num))
        {
            // make tentative assignment
            grid[row][col] = num;
 
            // return, if success, yay!
            if (SolveSudoku(grid))
                return true;
 
            // failure, unmake & try again
            grid[row][col] = UNASSIGNED;
        }
    }
    return false; // this triggers backtracking
}

网格总是作为参数传递给递归调用,因此每次迭代都有一个新的网格副本。

我似乎无法概念化使用相同逻辑在使用全局网格时是否有任何区别。

在失败条件之后,变量被设置为“取消制作并重试”——这不应该处理回溯中的任何“撤消”吗?

如果网格是全局的,这种递归回溯会有什么不同,为什么每次都发送和额外的副本?

【问题讨论】:

    标签: c algorithm search recursion artificial-intelligence


    【解决方案1】:

    网格总是作为参数传递给递归调用,所以 每次迭代都有一个新的网格副本。

    不,每次迭代都会有一个指向网格的引用(指针)的新副本。实际工作一遍又一遍地在同一个网格上完成。

    this code snap 为例:

    #include <stdlib.h>
    #include <stdio.h>
    void foo(int arr[], int n) {
        arr[0] = 1;
    }
    int main() {
        int myArray[5] = {0,0,0,0,0};
        foo(myArray,5);
        printf("%d",myArray[0]);
        return 0;
    }
    

    请注意,没有复制,foo() 中对arr 的更改反映到myArray

    一旦清楚这一点,我相信它会自动回答您的其余问题(这与使用全局变量基本相同,但全局变量通常是不好的做法,发送对数组的引用是更好的做法)。

    【讨论】:

    • 好的,我明白了,这就是我记得不久前的整个“数组是指针,有点像”。
    【解决方案2】:

    在 C/C++ 中,数组作为指向数组开头的指针传递。看看这个例子:

    #include <iostream>
    
    static const int N = 10;
    
    void test(int a[N][N])
    {
        std::cout << a << std::endl;
    }
    
    int main(int argc, char **argv)
    {
        int a[N][N];
        std::cout << a << std::endl;
        test(a);
        return 0;
    }
    

    如果你运行它,你会在标准输出上得到相同的值:

    $ ./test    
    0x7fff0c669930
    0x7fff0c669930
    

    这是指向数组开头的指针的值,所以在main()和test()中使用的是同一个指针。

    这意味着将网格设为全局变量不会获得任何性能提升。相反,您会通过引入全局变量来松散模块化。

    【讨论】:

    • 谢谢,我刚刚在 StackOverflow 上开了一个帐户 :)
    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多