POJ1321 chessboard (DFS)

Description

In a checkerboard given shape (the shape may be irregular) placed above the pieces, pieces no difference. The requirements of any two pieces can not be placed in the same row or the same column in the board when the display is required, program for solving a given board size and shape, placing the k pieces of all possible placement scheme C.

Input

Test input comprising a plurality of sets of data. 
The first line of each data are two positive integers, NK, separated by a space, and indicates the number of the board will be described in a matrix of n * n, and put the pieces. n <= 8, k <=  n
when the end of input is represented by -1 -1. 
Then n lines describe the shape of a checkerboard: n characters per line, where # represents the board area, indicates a blank area (extra blank line data is guaranteed not to appear or blank columns). 

Output

For each set of data, one line of output is given, the number of output display program C (data guarantee C <2 ^ 31).

Sample Input

2 1
#.
.#
4 4
...#
..#.
.#..
#...
-1 -1

Sample Output

2 
. 1 
Code:
 1 #include<iostream>
 2 #include<string.h>
 3 using namespace std;
 4 bool row[10];
 5 char a[8][8];
 6 int ans=0,n,k;
 7 bool check(int c,int i) {
 8     return !row[i]&&a[i][c]=='#';
 9 }
10 void  dfs(int c) {
11     if(k==0) {
12         ans++;
13         return;
14     }
15     if(c>=n) {
16         return;
17     }
18     for(int i=0; i<n; i++) {
19         if(check(c,i)) {
20             row[i]=true;
21             k--;
22             dfs(c+1);
23             row[i]=false;
24             k++;
25         }
26     }
27     dfs(c+1);
28 }
29 int main() {
30     bool flag=true;
31     while(flag) {
32         cin>>n>>k;
33         if(n==-1&&k==-1) {
34             return 0;
35         }
36         for(int i=0; i<n; i++) {
37             for(int j=0; j<n; j++) {
38                 cin>>a[i][j];
39             }
40         }
41         dfs(0);
42         cout<<ans<<endl;
43         memset(row,0,sizeof(row));
44         ans=0;
45     }
46 }

Ideas Analysis: Look from the column, the first column and then traverse the line, if this column is not a pawn and '#' point on further deep search to find the next column of point chessboard, the exit condition for dfs finished pieces and columns over the board under the column number.

Topic links: http://poj.org/problem?id=1321

Guess you like

Origin www.cnblogs.com/yuanhang110/p/11277435.html