POJ 1321 棋盘问题

#include<cstdio>
#include<cstring>
using namespace std;

char chess[10][10];
bool book[10];//记录此列有无被放置棋子
int n,k,num,way;

void dfs(int row){
    if(num==k){
        way++;
        return;
    }
    if(row>=n)   return;//从0开始
    for(int col=0;col<n;col++){
        if(!book[col]&&chess[row][col]=='#'){
            num++;
            book[col]=true;
            dfs(row+1);
            book[col]=false;//此时此节点的枝叶已经被搜索完毕,重置
            num--;
        }
    }
    dfs(row+1);//逐行放置棋子,遍历图表
}

int main(){
    while(~scanf("%d %d",&n,&k)&&n!=-1){
        way=num=0;
        memset(book,false,sizeof(book));
        memset(chess,'.',sizeof(chess));
        for(int i=0;i<n;i++)    scanf("%s",&chess[i]);
        dfs(0);
        printf("%d\n",way);
    }
    return 0;
}

猜你喜欢

转载自blog.51cto.com/13688928/2119235
今日推荐