c++ - 为什么我解决N个皇后区问题的回溯解决方案不起作用?

标签 c++ backtracking n-queens

这是当我通过传递args:0和board从主函数调用它时返回的输出,其中0是要从其开始的行号,而board是一个填充有零的4x4电路板:

9       1       1       1
1       1       9       1
1       1       1       1
1       0       1       1
注意:9表示皇后,而1表示被皇后攻击的单元格,0是既没有皇后也不受到皇后攻击的安全单元。
bool queen_placer(int row, std::vector<std::vector<int>> &board)
{
    if (row == board.size())
    {
        return true;
    }
    for (int col = 0; col < board[0].size(); col++)
    {
        bool safe = is_valid(row, col, board); //is_valid returns true if the position doesn't contain any queen and is not attacked by any queen
        if (safe)
        {
            board[row][col] = 9;
            value_assigner(row, col, board); //value assigner just assigns the attack values of the queen so placed
            if (queen_placer(row++, board))
            {
                return true;
            }
            else
            {
                continue;
            }
        }
    }
    return false;
}

最佳答案

您不是在回溯-回溯涉及撤消导致失败的选择,但是board[row][col]是永远的。
如果递归失败,则需要将开发板还原到以前的状态。

关于c++ - 为什么我解决N个皇后区问题的回溯解决方案不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64440654/

相关文章:

c++ - 如何在 C++ 中等待 mySQL 查询完成

c++ - 使用 std::async 引用对象

c++ - OpenCV计算时间检测特征

string - 如何生成多重集的所有排列?

python - 骑士之旅(含回溯)

java - 8 皇后算法 : Not getting full result set

algorithm - 更有效的算法来计算 N-queens 中的攻击?

c++ - Range-v3运算符重载以编写较短的代码

algorithm - 投资者和资金池 - 回溯

c++ - 对八皇后中的回溯感到困惑