#include <stdio.h> #include <stdlib.h> #define Maxsize 100 typedef struct node{ int _x; int _y; }chessman,*chess; static int cnt=0; static chessman c[Maxsize]; bool isOK(chess c,chessman cm,int c_len){ //判断是否能将当前皇后加入棋盘中 for(int i=0;i<c_len;i++){ if(c[i]._x==cm._x) return false; else if(c[i]._y==cm._y) return false; else if(abs(c[i]._x-cm._x)==abs(c[i]._y-cm._y)) return false; } return true; } void eight_queen(int k,int n,chess c){ //放置第k行的皇后 if(k>=n){ //k等于n则说明为满足条件的布局,则输出 cnt++; for(int m=0;m<n;m++){ printf("(%d,%d) ",c[m]._x,c[m]._y); } printf("\n"); }else{ for(int i=0;i<n;i++){ //循环枚举所有x的可能取值 chessman cm; cm._x=i; cm._y=k; if(isOK(c,cm,k)){ c[k]=cm; eight_queen(k+1,n,c); } } } } int main(){ eight_queen(0,8,c); printf("----------\n"); printf("COUNT = %d\n",cnt); return 0; }
时间: 2024-10-30 13:37:35