POJ 1321 棋盘问题

中文题, 题目不再解释, 简单dfs;
 
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cctype>

bool maps[10][10];//maps做棋盘,判断此点能不能下棋 maps[0][i]用来记录第i列能不能下棋
int n, k, ans, hang;//hang代表此刻在第几行下棋

void DFS(int k)
{
    if(k == 0) {//棋子放完
        ans++;
        return;
    }
    if(hang > n)//已检查行数大于等于n,此时k还未等于0;
        return;
    if(n - hang + 1 < k)//剩下行数不够棋子数
        return;
    hang++;
    for(int j = 1; j <= n; j++) {
        if(maps[0][j]) continue;
        if(!maps[hang][j]) continue;
        maps[0][j] = true;
        DFS(k - 1);
        maps[0][j] = false;
    }
    //如果此行没有棋子可放, 检查下一行
    DFS(k);
    hang--;
}

int main()
{
    char ch;
    while(~scanf("%d %d", &n, &k), n != -1 || k != -1) {
        memset(maps, false, sizeof(maps));
        ans = 0;
        for(int i = 1; i <= n; i++) {
            scanf(" ");
            for(int j = 1; j <= n; j++) {
                scanf("%c", &ch);
                if(ch == '#') maps[i][j] = true;
            }
        }
        
        hang = 1;
        for(int j = 1; j <= n; j++) {
            if(maps[0][j]) continue;
            if(!maps[hang][j]) continue;
            maps[0][j] = true;
            DFS(k - 1);
            maps[0][j] = false;//回溯
        }
        DFS(k);
        printf("%d\n", ans);
    }
}
原文地址:https://www.cnblogs.com/wangyuhao/p/4662087.html