八皇后问题-递归与非递归方法实现

本文介绍了使用递归和非递归方法解决八皇后问题的两种算法实现。递归方法通过深度优先搜索找到所有可能的解决方案;非递归方法则利用栈来记录每行的有效位置,实现了迭代式的回溯过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

int board[8][8];
int cnt = 0;

bool isValid(int i, int j)
{
    int k;
    for(k = 0; k < 8; ++k)
        if(k != j && board[i][k]) return false;
    for(k = 0; k < 8; ++k)
        if(k != i && board[k][j]) return false;
    for(k = 1; k < 8 && i-k >= 0 && j-k >= 0; ++k)
        if(board[i-k][j-k]) return false;
    for(k = 1; k < 8 && i-k >= 0 && j+k < 8; ++k)
        if(board[i-k][j+k]) return false;
    return true;
}

void queen_rec(int row)
{
    if(row == 8)
    {
        for(int i = 0; i < 8; ++i)
            for(int j = 0; j < 8; ++j)
                if(board[i][j]) printf("%d %d\n", i, j);
        printf("\n"); ++cnt;
    }
    else
    {
        for(int i = 0; i < 8; ++i)
        {
            if(isValid(row, i))
            {
                board[row][i] = 1;
                queen_rec(row+1);
                board[row][i] = 0;
            }
        }
    }
}

void queen_nonrec()
{
    //use stack to hold the previous valid position of each row
    int stack[8], row;
    for(row = 0; row < 8; ++row) stack[row] = -1;
    row = 0;
    //the row variable will decrease by 1 whenever backtracking happens. 
    //Finally, the row variable will become -1 and the loop should end there. 
    while(row >= 0)
    {
        if(row == 8)
        {
            for(int i = 0; i < 8; ++i)
            {
                for(int j = 0; j < 8; ++j)
                    if(board[i][j]) printf("%2d",1);
                    else printf("%2d", 0);
                printf("\n");
            }
            printf("\n"); ++cnt;
            --row;
        }
        else
        {
            //recover current position to be valid
            if(stack[row] >= 0 && stack[row] < 8) board[row][stack[row]] = 0;
            //try to find the next position available
            ++stack[row];
            while(stack[row] < 8 && !isValid(row, stack[row])) ++stack[row];
            //when come to the end of current row, set the position index of current row back to -1 and go to the upper row
            if(stack[row] >= 8) {stack[row] = -1; --row;}
            else
            {
                //found a valid position, go to the next row
                board[row][stack[row]] = 1; ++row;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值