K皇后问题递归解法
2015-04-27 23:41
260 查看
#include<iostream> #include<cmath> #include<ctime> using namespace std; bool check(int row,int *a) { for(int i=0;i<row;i++) if (a[i]==a[row] || fabs(a[i]-a[row])==fabs(i-row)) return false; return true; } void show(int *a,int num,int k) { cout<<"the "<<num<<" answer is:"<<endl; cout<<"-------------------"<<endl; for(int i=0;i<k;i++) for(int j=0;j<k;j++) { if (a[i]==j) cout<<'*'; else cout<<'o'; if ((j+1)%k==0) cout<<endl; } } void findpos(int row,int *a,int &num,int k) { if(row==k) { num+=1; show(a,num,k); } else{ for(int i=0;i<k;i++) { a[row]=i; if(check(row,a)) findpos(row+1,a,num,k); } } } int main(void) { int k; cout<<"the number of que is:"; cin>>k; int *a=new int[k];//记录每行皇后对应的列 int num=0;//记录解的数量 clock_t start,end; start=clock(); findpos(0,a,num,k); delete [] a; end=clock(); double totaltime=double((end-start))/CLOCKS_PER_SEC;//clock_t相当于long型 cout<<"time elapses "<<totaltime<<" seconds"; system("pause"); return 0; } View Code
View Code
利用位运算来计算K皇后问题解的个数,有些限制,是Matrix67提到的方法,bitmap的思想,速度快,内存小
#include<iostream> #include<ctime> using namespace std; void Queen(int column,int ld,int rd,int k, int &num) { //column,ld,rd中1表示禁位 int upperlim=(1<<k)-1;//01111 int pos,p; if(column!=upperlim)//列还有空位 { pos=upperlim & ~(column|ld|rd);//ld,rd? 取反后1表示可以放的位置 while(pos !=0) { p=pos & -pos;//01001->00001 取出最右面的一个1 pos-=p; Queen(column+p,(ld+p)<<1,(rd+p)>>1,k,num);//每向下移一行,对角线的禁位要要偏移一个单位 } //取完所有可放的位置 } else num+=1;// 当列放满时,一次大循环结束 } void ToTwo(int n) { for(int i=0;i<32;i++,n<<=1) cout<<(n<0); } int split(int n,int k) { return n & ((1<<k)-1); } int main(void) { clock_t start,end; int k,num=0; cout<<"皇后的数量:";//因为是用利用位代替了数组的传递,还有一位要用来移位时溢出 //这里int型决定了最大31个皇后 cin>>k; start=clock(); Queen(0,0,0,k,num); cout<<num<<endl; end=clock(); double totaltime=double(end-start)/CLOCKS_PER_SEC; cout<<"time elapse: "<<totaltime<<" seconds"<<endl; return 0; } //16个皇后,14772512,40s
相关文章推荐
- N皇后问题的递归与非递归解法
- n皇后问题的递归解法
- [LeetCode系列]N皇后问题递归解法 -- 位操作方式
- 八皇后问题(递归解法)
- n皇后问题的递归解法
- N皇后问题递归与非递归解法
- 算法学习记录 N皇后问题 递归解法
- 8皇后问题递归求解
- UVa 639 - Don't Get Rooked 类皇后问题 递归回溯
- HDOJ 2553 N皇后问题(递归)
- N皇后问题 递归回溯
- N皇后问题(递归回溯的学习)
- n皇后问题【非递归回溯】
- 递归与动态规划---N皇后问题的递归方法和位运算方法
- 递归---n皇后问题
- 称重问题递归解法
- [算法]简单的背包问题递归解法,C语言实现
- 八皇后问题 递归解法
- N皇后问题最简单解法
- 深度优先—递归方法 求解n皇后问题