八皇后问题-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;
}
相关文章推荐
- C++ 指针的常见错误
- HDU 5677
- c++第五次上机实验
- LINK1112:model machine type 'X86' conflicts with target machine type 'X64'
- C strpbrk 查找任意几个字符
- C++那些事儿
- C++子类调用父类构造函数
- C++标准库和STL的关系
- C strchr strrchr查找一个字符
- C++模板(一) ----函数模板
- 332. Reconstruct Itinerary(C++实现)
- C++程序设计语言练习5.2 内存对齐
- C 可指定长度的字符串函数
- C++内嵌汇编(一):反汇编分析C++代码
- c++中类的学习(一)
- C++里最容易忽视却不能忽视的问题(必看)
- 如何写cmake使其包含c++11特性 (-std=c++11如何写进cmakeList.txt)
- 334. Increasing Triplet Subsequence(C++实现)
- 【C++】int与string的互转
- MFC 中解析一个路径