递归系列-----------八皇后解法
2014-04-05 20:57
302 查看
#include <stdio.h>
#define N 8
typedef struct _tag_Pos
{
int ios;
int jos;
} Pos;
static char board[N+2][N+2];
static Pos pos[] = { {-1, -1}, {-1, 0}, {-1, 1} };
static int count = 0;
void init()
{
int i = 0;
int j = 0;
for(i=0; i<N+2; i++)
{
board[0][i] = '#';
board[N+1][i] = '#';
board[i][0] = '#';
board[i][N+1] = '#';
}
for(i=1; i<=N; i++)
{
for(j=1; j<=N; j++)
{
board[i][j] = ' ';
}
}
}
void display()
{
int i = 0;
int j = 1;
for(i=0; i<N+2; i++)
{
for(j=0; j<N+2; j++)
{
printf("%c", board[i][j]);
}
printf("\n");
}
}
int check(int i, int j)
{
int ret = 1;
int p = 0;
for(p=0; p<3; p++)
{
int ni = i;
int nj = j;
while( ret && (board[ni][nj] != '#') )
{
ni = ni + pos[p].ios;
nj = nj + pos[p].jos;
ret = ret && (board[ni][nj] != '*');
}
}
return ret;
}
void find(int i)
{
int j = 0;
if( i > N )
{
count++;
printf("Solution: %d\n", count);
display();
getchar();
}
else
{
for(j=1; j<=N; j++)
{
if( check(i, j) )
{
board[i][j] = '*';
find(i+1);
board[i][j] = ' ';
}
}
}
}
int main()
{
init();
find(1);
return 0;
}
#define N 8
typedef struct _tag_Pos
{
int ios;
int jos;
} Pos;
static char board[N+2][N+2];
static Pos pos[] = { {-1, -1}, {-1, 0}, {-1, 1} };
static int count = 0;
void init()
{
int i = 0;
int j = 0;
for(i=0; i<N+2; i++)
{
board[0][i] = '#';
board[N+1][i] = '#';
board[i][0] = '#';
board[i][N+1] = '#';
}
for(i=1; i<=N; i++)
{
for(j=1; j<=N; j++)
{
board[i][j] = ' ';
}
}
}
void display()
{
int i = 0;
int j = 1;
for(i=0; i<N+2; i++)
{
for(j=0; j<N+2; j++)
{
printf("%c", board[i][j]);
}
printf("\n");
}
}
int check(int i, int j)
{
int ret = 1;
int p = 0;
for(p=0; p<3; p++)
{
int ni = i;
int nj = j;
while( ret && (board[ni][nj] != '#') )
{
ni = ni + pos[p].ios;
nj = nj + pos[p].jos;
ret = ret && (board[ni][nj] != '*');
}
}
return ret;
}
void find(int i)
{
int j = 0;
if( i > N )
{
count++;
printf("Solution: %d\n", count);
display();
getchar();
}
else
{
for(j=1; j<=N; j++)
{
if( check(i, j) )
{
board[i][j] = '*';
find(i+1);
board[i][j] = ' ';
}
}
}
}
int main()
{
init();
find(1);
return 0;
}
相关文章推荐
- vbscript include的办法实现代码第1/2页
- PHP脚本中include文件出错解决方法
- Flex include和import ActionScript代码
- set_include_path在win和linux下的区别
- php include加载文件两种方式效率比较
- How to Auto Include a Javascript File
- 浅谈ASP.NET的include的使用方法
- java/jsp中 中文问题详解
- JSP计数器的制作
- php include和require的区别深入解析
- PHP include_path设置技巧分享
- JS 实现完美include载入实现代码
- IE不支持option的display样式,只能使用remove和add
- JS实现完美include加载功能代码
- Display SQL Server Login Mode
- js将控件隐藏的方法及display属性介绍
- Display SQL Server Version Information
- JSP开发入门(四)--JSP的内部对象
- 实战 J2EE 开发购物网站 二
- 解决CSS中 display 与 visibility 的区别