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

和八皇后问题基本类似,回溯算法搞定。//在poj提交时最好不要用布
//尔类型,ce过

#include 
#include 
#include 
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;
}

你可能感兴趣的:(acm之路,dfs/bfs)