题意:在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。
分析:
1、和八皇后很相似,一行一行的放,并判断该列是否放过。
2、唯一注意的是,因为要摆放的棋子数k可能小于棋盘的行数,所以不一定是从第一行开始放的,所以每行的情况都要搜一下。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
if(fabs(a - b) < eps) return 0;
return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 10000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
char pic[10][10];
int n, k;
int ans;
int vis[10];
void dfs(int x, int cur){
if(cur == k){
++ans;
return;
}
if(x >= n) return;
for(int i = 0; i < n; ++i){
if(!vis[i] && pic[x][i] == ‘#‘){
vis[i] = 1;
dfs(x + 1, cur + 1);
vis[i] = 0;
}
}
dfs(x + 1, cur);
}
int main(){
while(scanf("%d%d", &n, &k) == 2){
if(n == -1 && k == -1) return 0;
for(int i = 0; i < n; ++i){
scanf("%s", pic[i]);
}
memset(vis, 0, sizeof vis);
ans = 0;
dfs(0, 0);
printf("%d\n", ans);
}
return 0;
}
原文:http://www.cnblogs.com/tyty-Somnuspoppy/p/6657391.html