POJ 1321 棋盘问题 (dfs)

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放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

与炮台题类似
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue>
 4 #include<vector>
 5 #include<cstring>
 6 #include<string>
 7 #include<algorithm>
 8 #include<map>
 9 #include<cmath>
10 #include<math.h>
11 using namespace std;
12 
13 char chess[10][10];
14 long long res;
15 int n,K;
16 
17 bool judge(int x,int y)
18 {
19     for(int i=0;i<x;i++)
20         if(chess[i][y]=='C')
21             return false;
22     for(int j=0;j<y;j++)
23         if(chess[x][j]=='C')
24             return false;
25     return true;
26 }
27 
28 void dfs(int p,int k)//p表示棋盘中第几个位置(二维转一维),k表示第几个棋子
29 {
30     if(k==K)
31     {
32         res++;
33         return;
34     }
35     else if(p==n*n)
36         return;
37     else
38     {
39         int i,j;
40         i=p/n;
41         j=p%n;
42         if(chess[i][j]=='#'&&judge(i,j))
43         {
44             chess[i][j]='C';
45             dfs(p+1,k+1);
46             chess[i][j]='#';
47         }
48         dfs(p+1,k);
49     }
50 
51 }
52 
53 int main()
54 {
55 
56     while(~scanf("%d%d",&n,&K))
57     {
58         if(n==-1&&K==-1)
59             break;
60         for(int i=0;i<n;i++)
61             for(int j=0;j<n;j++)
62                 cin>>chess[i][j];
63         res=0;
64         dfs(0,0);
65         printf("%lld
",res);
66 
67     }
68     return 0;
69 }


 
原文地址:https://www.cnblogs.com/Annetree/p/7199030.html