这是我通过传递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;
}
答案 0 :(得分:1)
您没有回溯-回溯涉及撤消导致失败的选择,但是您的board[row][col]
是永远的。
如果递归失败,则需要将板恢复到以前的状态。
答案 1 :(得分:0)
以下是正确的代码,仅在第9行和第21行进行了更改,从而解决了此问题:
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++)
{
std::vector<std::vector<int>> board_prev = board; //Added line
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 + 1, board))
{
return true;
}
else
{
board = board_prev; //Added line
continue;
}
}
}
return false;
}
以下是此代码提供的输出:
1 9 1 1
1 1 1 9
9 1 1 1
1 1 9 1