码迷,mamicode.com
首页 > 其他好文 > 详细

K皇后问题递归解法

时间:2015-04-28 01:43:53      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 #include<iostream>
 2 #include<cmath>
 3 using namespace std;
 4 
 5 bool check(int row,int *a)
 6 {
 7     for(int i=0;i<row;i++)
 8         if (a[i]==a[row] || fabs(a[i]-a[row])==fabs(i-row))
 9             return false;
10     return true;
11 }
12 
13 void show(int *a,int num,int k)
14 {
15     cout<<"the %d answer is:";
16     cout<<num<<endl;
17     cout<<"-------------------"<<endl;
18     for(int i=0;i<k;i++)
19         for(int j=0;j<k;j++)
20         {
21             if (a[i]==j)
22                 cout<<*;
23             else cout<<o;
24             if ((j+1)%k==0)
25                 cout<<endl;
26         }
27 }
28 void findpos(int row,int *a,int &num,int k)
29 {
30     if(row==k)
31     {
32         num+=1;
33         show(a,num,k);
34     }
35     else{
36         for(int i=0;i<k;i++)
37         {
38             a[row]=i;
39             if(check(row,a))
40                 findpos(row+1,a,num,k);
41         }
42     }
43 }
44 int main(void)
45 {
46     int a[100]={0};//记录每行的皇后放哪一列
47     int k;
48     cout<<"the number of que is:";
49     cin>>k;
50     int num=0;
51     findpos(0,a,num,k);
52     system("pause");
53     return 0;
54 }
55 
56         
57         
View Code

 

K皇后问题递归解法

标签:

原文地址:http://www.cnblogs.com/fkissx/p/4461798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!