POJ 1321 棋盘问题 DFS 期末前水一水就好……

A - 棋盘问题
Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u
Submit Status

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
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
typedef long long ll;
using namespace std;
//freopen("D.in","r",stdin);
//freopen("D.out","w",stdout);
#define sspeed ios_base::sync_with_stdio(0);cin.tie(0)
#define maxn 10
const int inf=0x7fffffff;   //无限大
char board[maxn][maxn];
int place[maxn];
int n,k;
int cnt,num;

void dfs(int i)
{
    if(k==num)
    {
        cnt++;
        return;
    }
    if(i>=n)
        return;
    for(int j=0;j<n;j++)
    {
        if(!place[j]&&board[i][j]=='#')
        {
            place[j]=1;
            num++;
            dfs(i+1);
            place[j]=0;
            num--;
        }
    }
    dfs(i+1);
}
int main()
{
    while(cin>>n>>k)
    {
        if(n==-1&&k==-1)
            break;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
                cin>>board[i][j];
        }
        memset(place,0,sizeof(place));
        cnt=0;
        num=0;
        dfs(0);
        cout<<cnt<<endl;
    }
    return 0;
}

 

posted @ 2014-12-17 00:19  qscqesze  阅读(279)  评论(0编辑  收藏  举报