/*
**8皇后问题
**
*/
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 8
int gEightQueen[MAXSIZE] = {0}; //数组下标代表行数,数组内存储的数据代表列数
int gCount = 0; //记录可行的情况数
void print(){ //输出矩阵'*'出放置皇后,'0'处不放置东西
int i,j;
for(i = 0; i < MAXSIZE; i++){
for(j = 0; j < gEightQueen[i]; j++)
printf("0 ");
printf("* ");
for(j = gEightQueen[i] + 1; j < MAXSIZE; j++)
printf("0 ");
printf("\n");
}
printf("________________________________\n");
}
bool posVaild(int row, int col){
int rowIndex, colIndex;
for(rowIndex = 0; rowIndex < row; rowIndex++){
colIndex = gEightQueen[rowIndex];
if(colIndex == col){ //同列
return 0;
}
if((rowIndex - row) == (colIndex - col)){ //对角线
return 0;
}
if((rowIndex - row) == -(colIndex - col)){ //对角线
return 0;
}
}
return 1;
}
void EightQueen(int row){
int column;
for(column = 0; column < MAXSIZE; column++){
if(posVaild(row,column)){ //如果(row,column)可以放置皇后
gEightQueen[row] = column; //记录行号为row处放置皇后的列号为column
if(row == 7){ //行号0-7都已放置完
++gCount; //记录值加一
print(); //输出棋盘
gEightQueen[row] = 0; //把gEightQueen重置为0
return ;
}
EightQueen(row + 1); //对下一行进行处理
gEightQueen[row] = 0; //把gEightQueen重置为0
}
}
}
int main(){
EightQueen(0);
printf("total:%d\n",gCount);
return 0;
}
八皇后问题
最新推荐文章于 2020-12-03 22:39:19 发布