POJ1321 棋盘问题 搜索

  非常简单的一道搜索题,用状态压缩加DP写了一上午,写道后面越来越感觉这题状态压缩没有什么优势,每一行都与前面的行的排列有关系,因此不能够记忆化,没算完一次要把状态清空,可惜到最后还是错了。干脆直接暴力搜索。就这样过了。

代码如下:

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

int N, K, hash_x[10], hash_y[10], ans;

char G[10][10];

void dfs(int x, int y, int k)
{
    if (k == 0) {
        ++ans;
    }
    for (int i = x+1; i <= N; ++i) {
        for (int j = 1; j <= N; ++j) {
            if (!hash_x[i] && !hash_y[j] && G[i][j] == '#') {
                hash_x[i] = 1, hash_y[j] = 1;
                dfs(i, j, k-1);
                hash_x[i] = hash_y[j] = 0;
            }
        }
    }
}

int main()
{
    while (scanf("%d %d", &N, &K), N!=-1||K!=-1) {
        ans = 0;
        memset(hash_x, 0, sizeof (hash_x));
        memset(hash_y, 0, sizeof (hash_y));
        for (int i = 1; i <= N; ++i) {
            scanf("%s", G[i]+1);
        } 
        for (int i = 1; i <= N; ++i) {
            for (int j = 1; j <= N; ++j) {
                if (G[i][j] == '#') {
                    hash_x[i] = 1, hash_y[j] =1;
                    dfs(i, j, K-1);
                    hash_x[i] = hash_y[j] = 0;
                }
            }
        }
        printf("%d\n", ans);
    }
}
/*
8 4
.##.###..
.##...#..
..##..#..
.##..#..
..#.###..
.##..##..
.#.#..#..
.##.#.#..

2907
*/
原文地址:https://www.cnblogs.com/Lyush/p/2590329.html