n皇后问题(简单dfs)
2016-03-31 12:35
246 查看
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<string>
#include<set>
#include<sstream>
using namespace std;
int c[20];
int n;
int ans=0;
void dfs(int row)
{
if(row==n)
{
ans++;
return ;
}
for(int i=0;i<n;i++)
{
int ok=1;
c[row]=i;
for(int j=0;j<row;j++)
{
if(c[row]==c[j]||row+c[row]==j+c[j]||row-c[row]==j-c[j])
{
ok=0;
break;
}
}
if(ok)
{
dfs(row+1);
}
}
}
int main()
{
while(~scanf("%d",&n))
{
dfs(0);
printf("%d\n",ans);
}
return 0;
}
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<string>
#include<set>
#include<sstream>
using namespace std;
int c[20];
int n;
int ans=0;
void dfs(int row)
{
if(row==n)
{
ans++;
return ;
}
for(int i=0;i<n;i++)
{
int ok=1;
c[row]=i;
for(int j=0;j<row;j++)
{
if(c[row]==c[j]||row+c[row]==j+c[j]||row-c[row]==j-c[j])
{
ok=0;
break;
}
}
if(ok)
{
dfs(row+1);
}
}
}
int main()
{
while(~scanf("%d",&n))
{
dfs(0);
printf("%d\n",ans);
}
return 0;
}
相关文章推荐
- orcale基本函数1_--NULL值校验
- TuShare(3):使用pandas 压缩存储hdf5文件
- 270. Closest Binary Search Tree Value
- Ehcache memcache redis 三大缓存
- 复制构造函数
- 服务器编程之sessionID 和 账户id
- hdu4616(树形dp)
- java语言中不允许嵌套定义
- Jsp的四大作用域与九大对象
- LeetCode201 Bitwise AND of Numbers Range Java 题解
- Android实现下拉刷新上拉加载(PullToRefreshLayout)
- 第18章读书笔记
- RecyclerView的基本使用
- sqlite
- 二级菜单总结
- 通过Reactivecocoa绑定UISwitch到NSUserDefault
- 旧手机也可以变宝贝,95%的人不知道!
- [leetcode]151. Reverse Words in a String
- BZOJ 3333 排队计划 树状数组+线段树
- 有关线程安全的探讨--final、static、单例、线程安全