POJ 1321 棋盘问题 (DFS)


**链接 : ** Here!

**思路 : ** 这道题类似 $N$ 皇后, 只不过每一行并不是必须有一个棋子, 所以仍然是枚举每一行 $x$ , 1. 对于下棋的策略来说, 枚举每一列, 检查下棋点是否合法, 如果合法则搜索下一行, 并且标记, 等到搜索下一行的所有状态搜索完成, 取消标记, 进行回溯. 2. 对于不下棋的策略, 直接搜索下一行即可.


/*************************************************************************
	> File Name: E.cpp
	> Author: 
	> Mail: 
	> Created Time: 2017年11月26日 星期日 10时51分05秒
 ************************************************************************/

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

#define MAX_N 10
int n, k;
int sx, sy;
int vis1[MAX_N], vis2[MAX_N];
int dx[8] = {0, 0, -1, 1, -1, 1, 1, -1};
int dy[8] = {1, -1, 0, 0, -1, 1, -1, 1};
int total_num;
char G[MAX_N][MAX_N];

bool check(int x, int y) {
    if (x < 0 || x >= n || y < 0 || y >= n) return false;
    if (G[x][y] != '#') return false;
    if (vis1[x] || vis2[y]) return false;
    return true;
}
void setPoint(int x, int y) {
    vis1[x] = vis2[y] = 1;
}
void movePoint(int x, int y) {
    vis1[x] = vis2[y] = 0;
}
void DFS(int x, int cnt) {
    if (cnt == k) {
        ++total_num;
        return;
    }
    if (x >= n)   return;
    // 这一层放棋子
    for (int j = 0 ; j < n ; ++j) {
        if (!check(x, j)) continue;
        setPoint(x, j);
        DFS(x + 1, cnt + 1);
        movePoint(x, j);
    }
    // 这一层不放棋子
    DFS(x + 1, cnt);
    return;
}
void solve() {
    total_num = 0;
    DFS(0, 0);
    printf("%d
", total_num);
}
void read() {
    for (int i = 0 ; i < n ; ++i) {
        getchar();
        scanf("%s", G[i]);
    }
}
int main() {
    // freopen("./in.in", "r", stdin);
    while (scanf("%d%d", &n, &k) != EOF) {
        if (n == -1 && k == -1) break;
        memset(G, 0, sizeof(G));
        memset(vis1, 0, sizeof(vis1));
        memset(vis2, 0, sizeof(vis2));
        read();
        solve();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/WArobot/p/7903401.html