棋盤問題
?POJ - 1321?
在一個給定形狀的棋盤(形狀可能是不規則的)上面擺放棋子,棋子沒有區別。要求擺放時任意的兩個棋子不能放在棋盤中的同一行或者同一列,請編程求解對于給定形狀和大小的棋盤,擺放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
簡單的深搜模板題,下面是我自己寫的代碼:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define lep(i,l,r) for(int i=l;i>=r;i--)
#define ms(arr) memset(arr,0,sizeof(arr))
priority_queue<int,vector<int> ,greater<int> >q;
const int maxn = (int)1e5 + 5;
const ll mod = 1e9+7;
char mapp[10][10];
bool visited[10];
int n,k;
int step;
int num;
void dfs(int x)
{if(step==k){num++;return;}if(x>=n)return;rep(i,0,n-1) {if(visited[i]==false&&mapp[x][i]=='#'){step++;visited[i]=true;dfs(x+1);step--;visited[i]=false;}}dfs(x+1);
}
int main()?
{//freopen("in.txt", "r", stdin);//freopen("out.txt", "w", stdout);ios::sync_with_stdio(0),cin.tie(0);while(cin>>n>>k&&n!=-1&&k!=-1){ms(mapp);memset(visited,false,sizeof(visited));rep(i,0,n-1) {scanf("%s",mapp[i]);}num=0,step=0;dfs(0);cout<<num<<endl;}return 0;
}
?