POJ 1321 棋盘问题

题目链接:POJ 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

题意

给定一个矩阵的棋盘,棋盘形状不规则,即有的格子可以放棋子,有的不可以,要保证每行每列都只有一个棋子,问有几种摆放方法。

题解:

有点像八皇后问题,DFS跑,用一个vis[i]数组保存第i列是否已经有棋子了,然后一行一行去DFS,符合条件sum++,最后输出结果。

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<cstring>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>

using namespace std;

typedef long long ll;

const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 5;
int n, k;
char feld[9][9];
int vis[9];
int sum;
int way;
void dfs(int x) {
	if (way == k) {
		sum++;
		return;
	}
	if (x == n)
		return;
	for (int i(0); i<n; i++)
		if (vis[i] == 0 && feld[x][i] == '#') {
			vis[i] = 1;
			way++;
			dfs(x + 1);
			vis[i] = 0;
			way--;

		}
	dfs(x + 1);
}
int main() {
	while (cin >> n >> k, n != -1) {
		memset(feld, 0, sizeof feld);
		memset(vis, 0, sizeof vis);
		sum = 0;
		for (int i(0); i < n; i++)
			cin >> feld[i];
		way = 0;
		dfs(0);
		cout << sum << endl;
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Titordong/p/9592592.html