c语言八皇后问题

在国际象棋里面,皇后是最具有杀伤力的武器,它可以对它的十字形和对角线元素进行攻击。

八皇后问题就是在8*8的棋盘上的每一行都放置一个皇后,使他们无法进行互相攻击


思路:

1.编写一个函数,将一个皇后放在第一列,如果存在攻击就把皇后放在第二列,如果每列都存在互相攻击的情况,则这个函数返回

2.若皇后可以放在这个位置,则应该递归的调用本身,把皇后放在下一行,当递归函数返回时候,就证明本行这个位置放置导致下一行皇后无处可放,则将本行皇后向后移动一个位置,判断是否可以放置皇后,如果可以则进入递归函数里面,若不可以则在将本行皇后向后挪动一列

首先我们应该编写检查函数:

int isSafe(int (*chess)[EIGHT], int row, int col)
{
	int rowIndex;
	int colIndex;
	
	for(rowIndex = row-1; rowIndex >= 0; rowIndex--){//直上方
			if(chess[rowIndex][col])
				return FALSE;
void eightQueen(int (*chess)[EIGHT], int row)
{

	int colIndex;
	
	if(row >= EIGHT){
		showChess(chess);
	}
	else{
		for(colIndex = 0; colIndex < EIGHT; colIndex++){
			//chess[row][colIndex] = 1;
			if(isSafe(chess, row, colIndex) == TRUE){//如果可以放置皇后
				chess[row][colIndex] = 1;//放置皇后
				eightQueen(chess, row+1);//进行递归
				chess[row][colIndex] = 0;//递归返回时,证明此列不适合,下一列放置皇后
			}
		}
	}
}



递归函数:
void eightQueen(int (*chess)[EIGHT], int row)
{

	int colIndex;
	
	if(row >= EIGHT){
		showChess(chess);
	}
	else{
		for(colIndex = 0; colIndex < EIGHT; colIndex++){
			//chess[row][colIndex] = 1;
			if(isSafe(chess, row, colIndex) == TRUE){//如果可以放置皇后
				chess[row][colIndex] = 1;//放置皇后
				eightQueen(chess, row+1);//进行递归
				chess[row][colIndex] = 0;//递归返回时,证明此列不适合,下一列放置皇后
			}
		}
	}

输出函数:


void showChess(int (*chess)[EIGHT]){
	int i;
	int j;
	static int count;

	printf("解%d:\n", ++count);
	for(i = 0; i < EIGHT; i++){
		for(j = 0; j < EIGHT; j++){
			printf("%4d", chess[i][j]);
		}
		printf("\n");
	}
}

主函数:
void main()
{
	int chess[EIGHT][EIGHT] = {0};//定义并且初始化棋盘
	
	eightQueen(chess, 0);//进行处理
	
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值