回溯法解八皇后问题
{ printf(" ");
fprintf(fp," ");
}
printf("%d\n", i);
fprintf(fp, "%d\n", i);
}
printf
(".......................................................\n");
fprintf(fp,
/*/
#include <stdio.h>
#include <math.h>
#define false 0
#define true 1
#define quesize 8
int gx[quesize+1];
int sum=0;
int place( int k );
void print( int a[] );
fprintf(fp,"the sum of the ways of queens:%d\n", sum);
printf("the sum of the ways of queens:%d\n", sum);
fclose(fp);
return 1;
}
/*/////////////////////////////////////////////////////////////////////
{
int i = 1;
while ( i < k )
{ if ( ( gx[i] == gx[k] ) || ( abs( gx[i] - gx[k] )==abs( i - k ) )
)
return (false);
i = i + 1;
}
return (true);
}
/*/////////////////////////////////////////////////////////////////////
///
Resove the ways of n queens
///////////////////////////////////////////////////////////////////////
/*/
void nqueens( int n )
{ int k = 1;
gx[1] = 0;
while ( k > 0 )
//
If a queen in k row and gx[k] column then return 1 else return 0
///////////////////////////////////////////////////////////////////////
*/
int place( int k )
"........................................................\n");
fprintf
(fp,".....................................................\n");
sum = sum + 1;
}
*/
void print( int a[] )
{ int i,j;
printf("The %dth\n", sum+1);
fprintf(fp, "The %dth\n", sum+1);
for ( i = 1; i <= quesize; i++ )
{
for ( j = 1;j <= a[i]; j++)
///////
/////Completed date: 2007.12 ////////
/////Version number: Turboc 2.0
////////
///////////////////////////////////////////////////////////////////////
void nqueens( int n );
FILE *fp;
int main( )
{
system("cls");
fp = fopen("outfile.txt", "w");
if(!fp){
printf("the file can't be opened!");
return 0;
}
nqueens( quesize );
{ gx[k] = gx[k] + 1;
while ( ( gx[k] <= n ) && ( !place(k) ) )
gx[k] = gx[k] + 1;
if ( gx[k] <= n )
if ( k == n ) print(gx);
else {k = k + 1; gx[k] = 0;}
else k = k - 1;
}
}
/*////////////////////////////////////////
//
Print the results into outfile and screen.
///////////////////////////////////////////////////////////////////////
/*/////////////////////////////////////////////////////////////////////
///
/////The programming is a complex problem about the ways of
queens.///////
/////Programmer: Luo Xiaochun
回溯法解八皇后问题
在N * N格的棋盘上放置彼此不受攻击的N个皇后。N个皇后问题等价于在N * N格的棋盘上放置N个皇后,任何2个皇后不在同一行或同一列或同一斜线上。当N等于8,就是著名的八皇后问题。
此问题是通过C语言程序编写的,在Turboc环境下完成实现的。输出结果见(输出结果。TXT文件)
详细代码为: