AI-N Queen Problem(dfs)
2015-09-16 16:37
615 查看
#include <cstdio>//the biggest N of this dfs method is 29(4s) #include <iostream> #include <algorithm> using namespace std; int col[50];//col[row] seems the col of queen in the row int n; bool check(int r,int c) { int i; for(i=1;i<r;i++)//make sure all the previous points are not conflict with the current one if(c==col[i]||(r-i)==abs(c-col[i]))//the cols and diagonal lines return false; return true; } bool dfs(int r) { col[r]++; col[r+1]=0;//when a queen is finding her place,next queen must not be set. if(check(r,col[r])&&col[r]<=n)//if the queen find her place { if(r==n)//if all queens have been set { int w; for(w=1;w<=n;w++) printf("(%d,%d) ",w,col[w]); cout<<endl; return true;//return true to the upper level,telling them the mission has been finished. } int j; for(j=1;j<=n;j++) if(dfs(r+1)) return true; } return false; } int main() { cin>>n; int i; for(i=1;i<=n;i++) col[i]=0;//queens haven't been set yet for(i=1;i<=n;i++) if(dfs(1)) return 0;//exit when finding the first path. }
相关文章推荐
- JS获取URL中参数值(QueryString)的4种方法分享
- EasyUI,comobox兼容可编辑和和下拉框
- `MQTTClient (~> 0.2.6)` required by `Podfile`
- 3.0新成员 -value,vector,map
- Sphinx/Coreseek 4.1 跑 buildconf.sh 一个错误,无法生成configure档
- 利用Global 的BeginRequest事件实现域名的重写
- HDU 4746 Mophues(莫比乌斯反演)
- 产品交互设计入门书籍推荐(亲自看过)
- UGUI之slider详解
- iOS UItextField 总结
- Using 1.7 requires compiling with Android 4.4 (KitKat); currently using API XX
- Auto Layout still required after sending -viewDidLayoutSubviews to the view controller. 终极解决方法
- js给文本框赋值 value与innerHTML
- inverse = “true” example and explanation
- UGUI4.6---InputField
- UITableView的使用详解
- UEditor编辑器实现编辑器自适应宽度的解决方案
- 安装protractor进行前端自动化测试-web ui自动化测试
- 修改EasyUI的目录树的图标
- easy ui datagrid 动态绑定数据并绑定链接,进行操作