n皇后问题中的函数调用自动发生

时间:2018-12-09 17:42:47

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

我找到了这段代码来查找n皇后问题的所有可能解决方案:

#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循环中的value列达到其最大值时,for循环结束时,执行将转到queen()函数的最后一行,然后再次进行至for循环的开始。当for循环结束时,不会进行递归。这怎么可能?

1 个答案:

答案 0 :(得分:0)

这是因为递归。您正在调用Queen(row + 1,n),这会将控件带到函数的开始。