#include
#include
void showQueen(int (*classBound)[8]); //点的输出
int isvaluse(int (*classBound)[8],const int row,const int col); // 点的比较,row为行,col为列
void EightQueen(int (*classBound)[8],int row);
int main(void)
{
int classBound[8][8] = {0};
EightQueen(classBound,0);
printf("运行结果存入到了G盘的test.txt文件中\n");
return 0;
}
/*void showQueen(int (*classBound)[8])
{
int i,j;
static int cnt = 1;
printf("\n this is %d probable\n",cnt++);
for(i = 0;i < 8;i++)
{
for(j = 0;j < 8; j++)
printf("%4d",classBound[i][j]);
printf("\n");
}
}*/
void showQueen(int (*classBound)[8])
{
FILE *fp;
int i,j;
static int cnt = 1;
fp = fopen("G:\\test.txt","at");
if(fp == NULL)
{
printf("\n 文件打开失败 \n");
exit(0);
}
fprintf(fp,"\n this is %d probable\n",cnt++);
for( i = 0 ; i < 8 ; i++)
{
for(j = 0 ;j < 8 ; j++)
fprintf(fp,"%4d",classBound[i][j]);
fprintf(fp,"\n");
}
}
int isvaluse(int (*classBound)[8],const int row,const int col)
{
int i,j,OK = 1;
for(i = row - 1; OK == 1 && i >= 0 ; i--) //判断该皇后之前的同一列上是否有皇后
{
OK = !classBound[i][col];
}
for(i = row-1,j = col-1; OK == 1 && i >= 0 && j >= 0; i--,j--) //判断斜率为-1的斜线上是否有皇后
{
OK = !classBound[i][j];
}
for(i = row-1,j = col + 1;OK == 1 && i >= 0 && j < 8; i--,j++) //判断斜率为1的斜线上是否有皇后
{
OK = !classBound[i][j];
}
return OK;
}
void EightQueen(int (*classBound)[8],int row)
{
int j;
if(row < 8)
{
for(j = 0; j < 8; j++)
{
if(isvaluse(classBound,row,j))
{
classBound[row][j] = 1;
EightQueen(classBound, row + 1);
classBound[row][j] = 0; //将本位置不放皇后,以便测试下一位置
} //从那个递归函数进去之后,处理完之后,返回你进入时的那个点,为下一步的测试作准备时就把那个点置0
}
}
else
{
showQueen(classBound);
}
}
阅读(1475) | 评论(1) | 转发(1) |