八皇后问题最简单的解法

#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;
}



你可能感兴趣的:(C语言,八皇后问题)