您的位置:首页 > 编程语言 > C语言/C++

八皇后问题-C语言求解

2016-05-13 11:34 417 查看

/*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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: