【发布时间】:2021-06-02 15:43:47
【问题描述】:
我对编码还很陌生,所以放轻松,但我正在研究 N Queen 问题,该问题需要为 n 大小的板提供大量解决方案,您可以在每行放置一个皇后。我的代码工作到 n=4,然后 n=5 输出 11 和输出 0 之后的所有 n。-1s 出现在位置 [] 中直到 n=5,然后它们不会输入到数组中。我现在很无能为力,因此不胜感激。
#include <iostream>
using namespace std;
//MAXROWS is same as MAXCOLUMNS or BOARDSIZE
const int MAXROWS = 20;
//queens' placements in each row
int placements[MAXROWS];
int n = 0;
int solutionsCount = 0;
bool canPlaceQueen(int row, int column)
{
for(int j = 0; j < row; j++)
if((placements[j] == column) // is there a queen in same column?
|| (abs(placements[j] - column) == abs(j-row))) // checks diagonals
return false; // column difference is same as row difference?
return true;
}
bool correctSolution()
{
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
if (placements[i] == placements[j])
{
return false;
}
}
for (int k = 0; k < n; k++)
{
if (placements[k] == -1)
{
return false;
}
}
return true;
}
void placeQueens(int row) {
//try to place queen in each column in current row
//then continue to explore: placeQueens(row+1)
//for each successful queen placement in final row, increment solutionsCount!
for (int i = 0; i < n; i++)
{
if (canPlaceQueen(row, i))
{
placements[row] = i;
if (row < n-1)
{
placeQueens(row+1);
}
}
else
{
placements[row] = -1;
}
if (correctSolution())
{
solutionsCount++;
cout << "add" << placements[0] << placements [1] << placements[2] << placements[3] << endl;
}
}
cout << "new" << placements[0] << placements [1] << placements[2] << placements[3] << endl;
for (int j = 0; j < n; j++)
{
placements[j] = 0;
}
}
int main() {
cout << "Enter the board size: ";
cin >> n;
placeQueens(0);
cout << "Number of solutions: " << solutionsCount << endl;
}
【问题讨论】:
-
我认为 correctSolution() 不起作用。放置数组告诉你皇后在哪一列上一行。想象一下n = 8。如果您在 (0,0) 上有一个皇后,即 Placements[0] = 0,而在 (7,7) 上有一个皇后,即 Placements[7] = 7,那么 Placements[0] 是 != 对 Placements[7],但这是一个无效的解决方案(同一对角线上的两个皇后)。您的检查仅检查两个皇后是否在同一列。实际上我认为你可以让整个对角线都充满皇后,它仍然可以通过检查。
-
几周前我在方案中做了这个问题。我的递归策略是从第 n 列开始,找到 n-1 列的解决方案列表(递归步骤)。然后我采用这些解决方案中的每一个并生成一个新的潜在解决方案,方法是在第 n 列的第 0 行放置一个女王并检查它,将女王更改为第 1 行并再次检查它等等。只保留那些有效的解决方案。假设网格是 8x8,所以函数从第 7 列开始,所以它只需要 6 列的解决方案(但仍然是 7 行!),这反过来又需要 5 列的解决方案等,向下和向后递归。