八皇后问题-C语言求解

/*0808 Eight queens puzzle*/

#include<stdio.h>

#include<stdbool.h>

void ShowBoard(int (*chess)[8]);                                       //Print a solution

bool AttackCalculate(int (*chess)[8],int row,int col);     //To determine a right place

void SetBoard(int (*chess)[8],int row);                             //To calculate all solutions

static int solutions=0;

int main(void)

{

int chess[8][8] = { 0 };

SetBoard(chess, 8);

if (solutions==0)

printf("So,eight queen problem hasn't a solution\n");

else

printf("Now,We get %d solutions upon\n",solutions);

return 0;

}

void ShowBoard(int (*chess)[8])

{

int count_row, count_col;

printf("We get a solution in the following\n");

for (count_row = 0; count_row < 8; count_row++)

{

for (count_col = 0; count_col < 8; count_col++)

printf("%d", *(*(chess + count_row) + count_col));

putchar('\n');

}

solutions++;

}

void SetBoard(int (*chess)[8],int row)

{

int the_column;

int the_row=row-1;

if (row != 1)

{

for (the_column = 0; the_column < 8; the_column++)

{

if(the_column>0)

*(*(chess + the_row) + the_column-1) = 0;

if (AttackCalculate(chess, the_row, the_column) ==false)

{

*(*(chess + the_row) + the_column) = 1;

SetBoard(chess, row-1);

}

}

*(*(chess + the_row) + the_column - 1) = 0;

}

else

{

for (the_column = 0; the_column < 8; the_column++)

{

if (AttackCalculate(chess, the_row, the_column) ==false)

{

*(*(chess + the_row) + the_column) = 1;

ShowBoard(chess);

*(*(chess + the_row) + the_column) = 0;

}

}

}

}

bool AttackCalculate(int (*chess)[8],int row,int col)

{

int coord_x, coord_y;

for (coord_x = col, coord_y = 0; coord_y < 8; coord_y++)

{

if (*(*(chess + coord_y) + coord_x) == 1)

return true;

}

for (coord_x = 0, coord_y = row; coord_x < 8; coord_x++)

{

if (*(*(chess + coord_y) + coord_x) == 1)

return true;

}

for (coord_x = col, coord_y = row; coord_x < 8&&coord_y < 8; coord_y++,coord_x++)

{

if (*(*(chess + coord_y) + coord_x) == 1)

return true;

}

for (coord_x = col, coord_y = row; coord_x >= 0 && coord_y >= 0; coord_y--, coord_x--)

{

if (*(*(chess + coord_y) + coord_x) == 1)

return true;

}

for (coord_x = col, coord_y = row; coord_x >= 0 && coord_y < 8; coord_y++, coord_x--)

{

if (*(*(chess + coord_y) + coord_x) == 1)

return true;

}

for (coord_x = col, coord_y = row; coord_x < 8 && coord_y >= 0; coord_y--, coord_x++)

{

if (*(*(chess + coord_y) + coord_x) == 1)

return true;

}

return false;

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值