POJ 1321 棋盘问题(dfs)

题目链接

解题思路

  从第一行开始枚举,每次枚举都记录下选择的列数,搜索出所有符合条件的状态

const int maxn = 1+10;
char g[maxn][maxn];
int n, k, ans; bool vis[maxn];
void dfs(int p, int cnt) {
    for (int i = 0; i<n; ++i)
        if (!vis[i] && g[p][i]=='#') {
            if (cnt==k) {
                ++ans; continue;
            }
            vis[i] = true;
            for (int j = p+1; j<=n-k+cnt; ++j) dfs(j, cnt+1);
            vis[i] = false;
        }
}
int main(void) {
    while(~scanf("%d%d", &n, &k) && (~n&&~k)) {
        for (int i = 0; i<n; ++i) scanf("%s", g[i]);
        if (k>n) printf("0\n");
        else {
            zero(vis);
            ans = 0;
            for (int i = 0; i<=n-k; ++i) dfs(i, 1);
            printf("%d\n", ans);
        }
    }
    return 0;
}
posted @ 2020-04-20 09:28  shuitiangong  阅读(82)  评论(0编辑  收藏  举报