POJ 1321 - 棋盘问题

本文探讨了一个类似于八皇后问题的棋盘摆放问题,要求在指定的不规则棋盘上放置棋子,使得任意两棋子不在同一行或列。通过深度优先搜索(DFS)算法实现解决方案,并给出了具体代码实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

棋盘问题

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 21574 Accepted: 10712

Description

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。

Input

输入含有多组测试数据。
每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n
当为-1 -1时表示输入结束。
随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。

Output

对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。

Sample Input

2 1
#.
.#
4 4
...#
..#.
.#..
#...
-1 -1

Sample Output

2
1

感觉和八皇后差不多,直接DFS,记得标记哪些行用过。


#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>

using namespace std;

//#define WIN
#ifdef WIN
typedef __int64 LL;
#define iform "%I64d"
#define oform "%I64d\n"
#define oform1 "%I64d"
#else
typedef long long LL;
#define iform "%lld"
#define oform "%lld\n"
#define oform1 "%lld"
#endif

#define S64I(a) scanf(iform, &(a))
#define P64I(a) printf(oform, (a))
#define S64I1(a) scanf(iform1, &(a))
#define P64I1(a) printf(oform1, (a))
#define FOR(i, s, t) for(int (i)=(s); (i)<(t); (i)++)

const int INF = 0x3f3f3f3f;
const double eps = 10e-9;
const double PI = (4.0*atan(1.0));

const int maxn = 20;
int n, k;
int ans;
char G[maxn][maxn];
int vis[maxn];

void dfs(int cur, int has) {
    if(cur > n) return ;
    if(has == k) {
        ans++;
        return ;
    }
    for(int i=0; i<n; i++) if(G[cur][i] == '#' && !vis[i]) {
        vis[i] = 1;
        dfs(cur+1, has+1);
        vis[i] = 0;
    }
    dfs(cur+1, has);
} 

int main() {

    while(scanf("%d%d", &n, &k) != EOF && !(n==-1 && k==-1)) {
        for(int i=0; i<n; i++) {
            for(int j=0; j<n; j++) {
                char c = getchar();
                while(c != '#' && c != '.') c = getchar();
                G[i][j] = c;
            }
        }
        ans = 0;
        memset(vis, 0, sizeof(vis));
        dfs(0, 0);
        printf("%d\n", ans);
    }
    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值