我正在使用C语言实现一个算法来解决N皇后问题。我的代码可以解决n=4的问题,但对于其他任何n值都无法工作。我认为问题可能出在打印代码上,但我不确定。我尝试更改for
循环中的条件,但没有找到有效的方法。同时,我还需要找到在解决过程中从解树中剪枝的节点数量。如何修复这个问题并找到被剪枝的节点计数?
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int count = 0;
void queens(int n, int row, int col[]);
int promising(int row, int col[]);
void usage(char *argv);
int main(int argc, char *argv[])
{
if (argc < 2) { usage(argv[0]); }
int n = atoi(argv[1]);
int col[n];
queens(n, 0, col);
}
void queens(int n, int row, int *col)
{
int index;
if (promising(row, col))
{
if (row == n)
{
printf("\nSolution %d\n------------\n", ++count);
for (int i = 1; i <= n; i++, putchar('\n')) // This works for n = 4.
{
for (int j = 0; j <= n - 1; j++) // This works for n = 4.
{
if (j == col[i]) { putchar('Q'); }
else { putchar('*'); }
}
}
return;
}
else
{
for (index = 0; index < n; index++)
{
col[row + 1] = index;
queens(n, row + 1, col);
}
}
}
}
int promising(int row, int *col)
{
int index;
int is_promising;
index = 0;
is_promising = 1;
while (index < row && is_promising)
{
if (col[row] == col[index] || abs(col[row] - col[index]) == row - index)
{
is_promising = 0;
}
index++;
}
return is_promising;
}
void usage(char *argv)
{
printf("usage: %s <number of queens>", argv);
exit(0);
}