poj1321 dfs

题意:略

记录棋盘上能放棋子的位置

用 col 和 row 数组记录某行某列是否已经有棋子了

然后简单的深搜,但是剪枝不知道怎么剪,status好多0ms 我的代码是32ms

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

struct point { int x, y; } pie[70];
int n, k, am;
char map[10][10];
bool col[10], row[10];

int dfs (int m, int left)
{
    if (left == 0) return 1;
    if (n - pie[m].x < left) return 0; //剪枝
    int i, tx, ty, ans = 0;

    for (i = m; i < am; i++) {
        tx = pie[i].x;
        ty = pie[i].y;
        if (!col[ty] && !row[tx]) {
            col[ty] = row[tx] = true;
            ans += dfs (i + 1, left - 1);
            col[ty] = row[tx] = false;
        }
    }
    return ans;
}

int main()
{
    while (scanf ("%d %d", &n, &k)) {
        if (n == -1 && k == -1) break;
        am = 0;
        getchar();
        for (int i = 0; i < n; i++)  {
            gets (map[i]);
            for (int j = 0; j < n; j++)
                if (map[i][j] == '#') {
                    pie[am].x = i;
                    pie[am++].y = j;
                }
        }
        memset (col, false, sizeof (col));
        memset (row, false, sizeof (row));
        printf ("%d\n", dfs (0, k));
    }
    return 0;
}



你可能感兴趣的:(poj1321 dfs)