八皇后问题最简单的解法

#include<stdio.h>

int chess[8][8];
int count = 0;

void display(){
	int row,col;
	for(row = 0; row < 8; row++){
		for(col = 0; col < 8; col++){
			if(chess[row][col] == 1){
				printf("%c ",45);
			}
			else if(chess[row][col] == 2){
				putchar(1);
				printf("%c",32);

			}

		}
		printf("\n");
	}
	getch();
}
void setLimitsArea(int row,int col){
	int i,j;
	for(j = 0; j < 8; j++)
		if(col != j)
			chess[row][j] = 1;
	for(i = 0; i < 8; i++)
		if(row != i)
			chess[i][col] = 1;
	for(i = 1; row - i >= 0 && col - i >= 0; i++)
		chess[row - i][col - i] = 1;
	for(i = row + 1,j = col + 1; i < 8 && j < 8; i++,j++)
		chess[i][j] = 1;
	for(i = 1; row - i >= 0 && col + i < 8; i++)
		chess[row - i][col + i] = 1;
	for(i = row + 1,j = col - 1; i < 8 && j >=0; i++,j--)
		chess[i][j] = 1;
}
void eightQueensProblem(){
	int row1,row2,row3,row4,row5,row6,row7,row8;
	int i, j;
	for(row1 = 0;row1 < 8;row1++){
		for(row2 = 0;row2 < 8;row2++){
			for(row3 = 0;row3 < 8;row3++){
				for(row4 = 0;row4 < 8;row4++){
					for(row5 = 0;row5 < 8;row5++){
						for(row6 = 0;row6 < 8;row6++){
							for(row7 = 0;row7 < 8;row7++){
								for(row8 = 0;row8 < 8;row8++){
									for(i = 0;i < 8;i++)
										for(j = 0;j < 8;j++)
											chess[i][j] = 0;
									chess[0][row1] = 2;
									setLimitsArea(0,row1);
									if(chess[1][row2] == 0){
										chess[1][row2] = 2;
										setLimitsArea(1,row2);
										if(chess[2][row3] == 0){
											chess[2][row3] = 2;
											setLimitsArea(2,row3);
											if(chess[3][row4] == 0){
												chess[3][row4] = 2;
												setLimitsArea(3,row4);
												if(chess[4][row5] == 0){
													chess[4][row5] = 2;
													setLimitsArea(4,row5);
													if(chess[5][row6] == 0){
														chess[5][row6] = 2;
														setLimitsArea(5,row6);
														if(chess[6][row7] == 0){
															chess[6][row7] = 2;
															setLimitsArea(6,row7);
															if(chess[7][row8] == 0){
																chess[7][row8] = 2;
																count = count + 1;
																printf("  NO %d Method   \n",count);
																display();
															}
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

int main(){
	int row = 0,col = 0;
	for(row = 0; row < 8; row++)
		for(col = 0; col < 8; col++)
			chess[row][col] = 0;
	eightQueensProblem();
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值