|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
参考了小甲鱼的代码,虽然有些地方看不懂
这里的left函数不是必须的,只是为了严谨
花了几天时间,想出来了感觉好有成就感
- #include <stdio.h>
- #define OCUR 'O' //该位置已有皇后
- #define NOTOCUR '*' //无皇后时数组的填充符号
- #define NUM 8 //皇后个数
- void Queen(int x,int y,char str[NUM][NUM]);// 求解函数
- void print(char str[NUM][NUM]);//打印解函数
- int left(int x,int y,char str[NUM][NUM]);//判断(x,y)的左侧是否已有皇后
- int top(int x,int y,char str[NUM][NUM]);//判断(x,y)的上侧是否已有皇后
- int left_top(int x,int y,char str[NUM][NUM]);//判断(x,y)的左上侧是否已有皇后
- int right_top(int x,int y,char str[NUM][NUM]);//判断(x,y)的右上侧是否已有皇后
- void init(char str[NUM][NUM]);//初始化,使棋盘上无皇后
- static int count = 0;//全局变量,用于记录已求解的个数
- int main(){
- char str[NUM][NUM];
- int x=0,y=0;
- while(x != NUM){
- printf("当x=%d时---->\n",x);
- init(str);
- Queen(x,y,str);
- x++;
- }
- printf("count = %d\n",count);
- return 0;
- }
- void init(char str[NUM][NUM]){
- int i,j;
- for(i=0;i<NUM;i++){
- for(j=0;j<NUM;j++){
- str[i][j] = NOTOCUR;
- }
- }
- }
- void print(char str[NUM][NUM]){
- printf("找到第%d组:\n",count);
- int i,j;
- for(i=0;i<NUM;i++){
- for(j=0;j<NUM;j++){
- printf("%c ",str[j][i]);
- }
- putchar('\n');
- }
- printf("*******************\n");
- }
- void Queen(int x,int y,char str[NUM][NUM]){
- if(top(x,y,str) && left(x,y,str) && left_top(x,y,str) && right_top(x,y,str)){
- str[x][y] = OCUR;
- y++;
- x=0;
- if(y == NUM){
- count++;
- print(str);
- return;
- }
- while(x != NUM){
- Queen(x,y,str);
- str[x][y] = NOTOCUR;
- x++;
- }
- }
-
- return;
- }
- int top(int x,int y,char str[NUM][NUM]){
- int j;
-
- for(j = y;j >= 0;j--){
- if(str[x][j] == OCUR){
- return 0;
- }
- }
-
- return 1;
- }
- int left(int x,int y,char str[NUM][NUM]){
- int i;
- for(i = x;i >= 0;i--){
- if(str[i][y] == OCUR){
- return 0;
- }
- }
-
- return 1;
- }
- int left_top(int x,int y,char str[NUM][NUM]){
- int i,j;
- for(i=x,j=y;i>=0 && j>=0;i--,j--){
- if(str[i][j] == OCUR){
- return 0;
- }
- }
- return 1;
- }
- int right_top(int x,int y,char str[NUM][NUM]){
- int i,j;
- for(i=x,j=y;i < NUM && j>=0;i++,j--){
- if(str[i][j] == OCUR){
- return 0;
- }
- }
-
- return 1;
- }
复制代码 |
|