Chinaunix首页 | 论坛 | 博客
  • 博客访问: 226250
  • 博文数量: 80
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 781
  • 用 户 组: 普通用户
  • 注册时间: 2014-11-08 10:41
个人简介

爱莉清

文章分类

全部博文(80)

文章存档

2018年(1)

2017年(18)

2016年(49)

2015年(7)

2014年(5)

我的朋友

分类: C/C++

2017-02-21 16:42:24

    八皇后问题是一个比较经典的算法问题。在看了别人的各种各样的程序算法之后。还是看不懂,最后我放弃了。看不懂那就自己推理吧。
其实八皇后问题最核心的还是使用递归,来计算。

以后再慢慢总结补充(^_^)

不啰嗦看代码

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<stdlib.h >

  3. #define M 8

  4. int buff[M][M];
  5. int sum=0;

  6. void Clear_Buff(void)
  7. {
  8.     int i,j;
  9.     for(i=0;i<M;i++)
  10.         for(j=0;j<M;j++)
  11.             buff[i][j] = 0;
  12. }

  13. void Disply(void)
  14. {
  15.     int i,j;

  16.     printf("----------------------\n");

  17.     for(i=0;i<M;i++)
  18.     {
  19.         for(j=0;j<M;j++)
  20.         {
  21.             printf(" %d",buff[i][j]);
  22.         }
  23.         printf("\n");
  24.     }
  25.     printf("----------------------\n");
  26. }

  27. int Is_OK(int x, int y)
  28. {
  29.     int i,j;

  30.     for(i=0;i<x;i++)
  31.     {
  32.         for(j=0;j<M;j++)
  33.         {
  34.             if(buff[i][j] ==1){
  35.                 if(abs(i-x) == abs(j-y) || (j==y)){
  36.                     return 0;
  37.                 }
  38.             }
  39.             
  40.         }
  41.     }
  42.     return 1;
  43. }

  44. void Search(int depth)
  45. {
  46.     int i,j;
  47.     for(i=0;i<M;i++){

  48.         if(Is_OK(depth, i)){
  49.             if(depth == M-1)
  50.             {
  51.                 sum++;
  52.                 buff[depth][i] = 1;
  53.                 printf("第%d种解法 \n",sum);
  54.                 Disply();
  55.                 buff[depth][i] = 0;
  56.                 return ;
  57.             }
  58.             buff[depth][i] = 1;
  59.             Search(depth+1);
  60.             buff[depth][i] = 0;
  61.         }

  62.     }
  63. }

  64. void main(void)
  65. {

  66.     printf("你好八皇后\n");
  67.     Clear_Buff();
  68.     Search(0);
  69.     printf("sum = %d\n",sum);
  70.     return ;
  71. }

阅读(1198) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~