您的位置:首页 > 其它

poj1321题解(也是我的第一篇博客)

2016-05-12 10:06 302 查看
和八皇后问题基本类似,回溯算法搞定。//在poj提交时最好不要用布

//尔类型,ce过

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
char chess[9][10];//最后一个放换行符
int n,k,count;

bool is_put(int row,int cline)
{
int i;
for(i=1;i<=n;i++)
if(!chess[i][cline]||!chess[row][i])
return false;
return true;
}
void dfs(int nrow,int hget)
{
int i,j;
if(hget==k) {
count++;
return;
}
for(i=nrow;i<=n;i++)
for(j=1;j<=n;j++)
{
if(chess[i][j]=='#')
{
if(is_put(i,j))
{
chess[i][j]='\0';
dfs(i+1,hget+1);
chess[i][j]='#';
}
}
}

}
int main(int argc, char const *argv[])
{
int i,j;
while(scanf("%d %d",&n,&k)==2&&n!=-1&&k!=-1)
{
getchar();//去掉第一行的换行符
memset(chess,0,sizeof(chess));
for(i=1;i<=n;i++)
for(j=1;j<=n+1;j++)
scanf("%c",chess[i]+j);
count=0;
dfs(1,0);
printf("%d\n",count );
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: