【问题标题】:Function call taking place automatically in n-queen problem在 n-queen 问题中自动发生函数调用
【发布时间】:2018-12-09 17:42:46
【问题描述】:

我找到了这段代码来找到一个 n-queen 问题的所有可能的解决方案:

#include<stdio.h>
#include<math.h>

int board[20], count;

int main()
{
    int n, i, j;
    void queen(int row, int n);

    printf(" - N Queens Problem Using Backtracking -");
    printf("\n\nEnter number of Queens:");
    scanf("%d", &n);
    queen(1, n);
    return 0;
}

//function for printing the solution
void print(int n)
{
    int i, j;
    printf("\n\nSolution %d:\n\n", ++count);

    for (i = 1; i <= n; ++i)
        printf("\t%d", i);

    for (i = 1; i <= n; ++i)
    {
        printf("\n\n%d", i);
        for (j = 1; j <= n; ++j) //for nxn board
        {
            if (board[i] == j)
                printf("\tQ"); //queen at i,j position
            else
                printf("\t-"); //empty slot
        }
    }


}

/*funtion to check conflicts
If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int row, int column)
{
    int i;
    for (i = 1; i <= row - 1; ++i)
    {
        //checking column and digonal conflicts
        if (board[i] == column)
            return 0;
        else
            if (abs(board[i] - column) == abs(i - row))
                return 0;
    }

    return 1; //no conflicts
}

//function to check for proper positioning of queen
void queen(int row, int n)
{
    int column;
    for (column = 1; column <= n; ++column)
    {
        if (place(row, column))
        {
            board[row] = column; //no conflicts so place queen
            if (row == n) //dead end
                print(n); //printing the board configuration
            else //try queen with next position
                queen(row + 1, n);
        }
    }
}

我的困惑是main()函数只调用了一次queen()函数,但是当queen()函数的for循环结束时,queen()函数又开始了。我通过调试看到,当for循环中的值列达到最大值时,for循环结束,执行到queen()函数的最后一行,然后再次进入for循环的开始。当 for 循环结束时,递归不会发生。这怎么可能?

【问题讨论】:

  • “这怎么可能?” 这叫做递归。
  • queen(row+1,n); :您在queen 函数内调用queen 函数。这叫做递归。
  • @πάνταῥεῖ 但是当 column=n 时,for 循环结束。它不调用queen(row+1,n)
  • queen() 函数在 column=n+1 时不会被调用。没有人明白我在说什么

标签: c++ function recursion call n-queens


【解决方案1】:

这是因为递归。您正在调用 queen(row+1,n),这会将控制权转移到函数的开头。

【讨论】:

  • OP 知道这一点。问题是为什么它似乎继续这样做,即使最终循环达到它的控制限制并中断。
  • 当列变量的值达到n且for循环结束时,不调用queen(row+1,n)
  • 我也尝试过调试,这只是因为每次调用女王函数时的递归,for循环将运行直到中断,一旦中断,前一个函数调用正在运行,它启动循环从头再来
  • @yogijain 您最后的评论实际上是 OP 正在寻找的答案,他们是否理解是另一回事。
猜你喜欢
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多