题目链接:http://poj.org/problem?id=1321
棋盘问题
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 Source |
[Submit] [Go Back] [Status] [Discuss]
题目大意:略
解析: #代表可以放棋子,用book[N} 标记下用过的列,扫描每一行,找到答案时,ans++
代码如下:
#include<iostream>
#include<algorithm>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<string>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#define N 19
using namespace std;
const int inf = 1e9;
const int mod = 1<<30;
const double eps = 1e-8;
const double pi = acos(-1.0);
typedef long long LL;
int mp[N][N], ans, n, d, book[N];
void dfs(int u, int cur)
{
if(cur == d) { ans++; return ; } // 达到要求,ans++, 返回
if(u == n + 1) return ;
for(int i = 1; i <= n; i++)
{
if(!book[i] && mp[u][i])
{
book[i] = 1;
dfs(u + 1, cur + 1);
book[i] = 0; // 回溯时用
}
}
dfs(u + 1, cur);//很重要,当前行没找到搜下一行,或者当前行搜完后搜下一行
return ;
}
int main()
{
int i, j;
char s;
while(scanf("%d%d", &n, &d), n + d != -2)
{
memset(mp, 0, sizeof(mp));
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
scanf(" %c", &s);
if(s == '#') mp[i][j] = 1; // 1 表示能放棋子
}
}
ans = 0;
memset(book, 0, sizeof(book)); // 将标记数组初始化,1表示走过, 0表示没走过
dfs(1, 0);
cout << ans << endl;
}
return 0;
}