Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1064132
  • 博文数量: 573
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 66
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-28 16:21
文章分类

全部博文(573)

文章存档

2018年(3)

2016年(48)

2015年(522)

分类: C/C++

2015-12-04 13:16:53

八皇后问题的非递归解法


  1. "color: rgb(51, 51, 51); font-family: 'Lucida Grande', Verdana, sans-serif; font-size: 13px; line-height: 19px; background-color: rgb(244, 244, 236);">用C++实现了八皇后问题的非递归算法。原理很简单,看代码就是了,无须多说  
  1. #include   
  2.   
  3. #include   
  4.   
  5. #include   
  6.   
  7. #include   
  8.   
  9.   
  10.   
  11. using namespace std;  
  12.   
  13. const int MAX = 8;  
  14.   
  15.   
  16.   
  17. vector<int> board(MAX);  
  18.   
  19.   
  20.   
  21. void show_result()  
  22.   
  23. {  
  24.   
  25.     for(size_t i = 0; i < board.size(); i++)  
  26.   
  27.         cout<<"("<","<")";  
  28.   
  29.     cout<
  30.   
  31. }  
  32.   
  33.   
  34.   
  35. int check_cross()  
  36.   
  37. {  
  38.   
  39.     for(size_t i = 0; i < board.size()-1; i++)  
  40.   
  41.     {  
  42.   
  43.         for(size_t j = i+1; j < board.size(); j++)  
  44.   
  45.         {  
  46.   
  47.             if((j-i) == (size_t)abs(board[i]-board[j]))  
  48.   
  49.                 return 1;  
  50.   
  51.         }  
  52.   
  53.     }  
  54.   
  55.     return 0;  
  56.   
  57. }  
  58.   
  59.   
  60.   
  61. void put_chess()  
  62.   
  63. {  
  64.   
  65.     while(next_permutation(board.begin(), board.end()))  
  66.   
  67.     {  
  68.   
  69.         if(!check_cross())  
  70.   
  71.         {  
  72.   
  73.             show_result();  
  74.   
  75.         }  
  76.   
  77.     }  
  78.   
  79. }  
  80.   
  81.   
  82.   
  83. int main()  
  84.   
  85. {  
  86.   
  87.     for(size_t i =0; i < board.size(); i++)  
  88.   
  89.         board[i] = i;  
  90.   
  91.     put_chess();  
  92.   
  93.     return 0;  
  94.   
  95. }  
阅读(541) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~