在NN的国际象棋棋盘上,如何放置N个皇后,使其不相互攻击。 要求: 1)编写第k号皇后是否可放置在棋盘上的判定算法:bool Placed(int k); 2)编写实现前stop个皇后能否放置的随机算法bool nQueenLV(int stop); 3)编写实现后step到N号皇后能否放置的非递归回溯算法bool Backtrack(int step); 4)编写bool nQueen()函数,调用2)和3)算法,将结果打印到文件(Queen.txt)
时间: 2024-03-21 21:41:44 浏览: 15
好的,我知道了。这是一个经典的问题,我会为您解答。以下是代码实现:
1)判定算法Placed(int k):
```cpp
bool Placed(int k, int* x)
{
for (int i = 0; i < k; i++) {
if (x[i] == x[k] || abs(x[i] - x[k]) == abs(i - k)) {
return false;
}
}
return true;
}
```
其中,x数组记录了每一行皇后所在的列数。
2)随机算法nQueenLV(int stop):
```cpp
bool nQueenLV(int stop)
{
srand((unsigned)time(NULL));
int* x = new int[stop];
memset(x, 0, sizeof(int) * stop);
int k = 0;
while (k >= 0 && k < stop) {
int i = rand() % stop;
x[k] = i;
if (Placed(k, x)) {
k++;
}
}
if (k == stop) {
ofstream outfile("Queen.txt");
for (int i = 0; i < stop; i++) {
for (int j = 0; j < stop; j++) {
if (x[i] == j) {
outfile << "Q ";
}
else {
outfile << ". ";
}
}
outfile << endl;
}
outfile.close();
delete[] x;
return true;
}
else {
delete[] x;
return false;
}
}
```
其中,使用随机算法生成每一行皇后所在的列数,然后调用Placed函数进行判断,如果能够放置,则将k加1;如果不能放置,则重新生成列数。
3)非递归回溯算法Backtrack(int step):
```cpp
bool Backtrack(int step, int* x)
{
int n = step;
int k = 0;
x[k] = -1;
while (k >= 0) {
x[k]++;
while (x[k] < n && !Placed(k, x)) {
x[k]++;
}
if (x[k] < n) {
if (k == n - 1) {
ofstream outfile("Queen.txt");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (x[i] == j) {
outfile << "Q ";
}
else {
outfile << ". ";
}
}
outfile << endl;
}
outfile.close();
return true;
}
else {
k++;
x[k] = -1;
}
}
else {
k--;
}
}
return false;
}
```
其中,使用非递归回溯算法生成每一行皇后所在的列数,然后调用Placed函数进行判断。
4)调用nQueenLV和Backtrack函数的nQueen函数:
```cpp
bool nQueen()
{
int n = 8; // 棋盘大小
int* x = new int[n];
memset(x, 0, sizeof(int) * n);
bool result = nQueenLV(n);
if (!result) {
result = Backtrack(n, x);
}
delete[] x;
return result;
}
```
其中,先调用随机算法nQueenLV函数,如果无法找到解,则调用非递归回溯算法Backtrack函数。最后将结果打印到文件Queen.txt中。
注意:以上代码仅供参考,可能存在错误或不足之处,具体实现需要根据实际情况进行调整。