八皇后问题的后续更新
Posted 离愁i
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了八皇后问题的后续更新相关的知识,希望对你有一定的参考价值。
在一个c文件中实现八皇后的问题:
#include<stdio.h>
#define EIGENT 8
bool isSafe(int (*chessboard)[EIGENT],const int row, const int col);
void orderQueen(int(*chessboard)[EIGENT],const int row);
void drawChessboard(int(*chessboard)[EIGENT]);
bool isSafe(int (*chessboard)[EIGENT],const int row, const int col){
int i;
int j;
for(i = row -1,j = col - 1;i >= 0 && j >= 0;i--,j--){
if(chessboard[i][j] == 1){
return false;
}
}
for(i = row - 1,j = col;i >= 0;i--){
if(chessboard[i][j] == 1){
return false;
}
}
for(i = row - 1,j = col + 1;i >= 0 && j < EIGENT; i-- , j++){
if(chessboard[i][j] == 1){
return false;
}
}
return true;
}
void orderQueen(int(*chessboard)[EIGENT],const int row){
static int count = 0;
if(row >= EIGENT){
++count;
drawChessboard(chessboard);
}else{
int col;
for(col = 0; count < 23 && col < EIGENT;col++){ //输出23种结果!
chessboard[row][col] = 1;
if(isSafe(chessboard,row,col)){
orderQueen(chessboard,row + 1);
}
chessboard[row][col] = 0;
}
}
}
void drawChessboard(int(*chessboard)[EIGENT]){
int row;
int col;
static int count = 0;
printf("第%d个解:\n",++count);
for(row = 0; row < EIGENT; row++) {
for(col = 0; col < EIGENT; col++) {
printf("%2d", chessboard[row][col]);
}
printf("\n");
}
}
int main(){
int chess[EIGENT][EIGENT] = {0};
orderQueen(chess,0);
return 0;
}
以上是关于八皇后问题的后续更新的主要内容,如果未能解决你的问题,请参考以下文章