这是当我通过传递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/