POJ 1321 DFS backtracking + recursive enumeration checkerboard issues
Time Limit: 1000MS |
|
Memory Limit: 10000K |
Total Submissions: 24813 |
|
Accepted: 12261 |
Description
In a given shape of the chessboard (the shape may be irregular) on the top of the pieces, chess pieces no difference. If you need to place any of the two pieces in the same row or column in the chessboard, please program the chessboard with a given shape and size, and put all the feasible arrangement C for the K pieces.
Input
The input contains multiple sets of test data.
The first row of each set of data is two positive integers, n K, separated by a space, indicating that the chessboard will be described in a n*n matrix and the number of pieces to be placed. N <= 8, K <= N
When 1-1 indicates the end of the input.
The next n lines describe the shape of the chessboard: N characters per line, where # represents the board area. Represents an empty area (the data guarantees that no extra blank lines or blank columns appear).
Output
For each set of data, give a line of output, the output is placed in the number of programs C (Data Assurance c<2^31).
Sample Input
2 #.. #4 4...#. #.. #.. #...-1-1
Sample Output
21st
Idea: Using the method of N queen problem, Dfs backtracking is carried out in line order, and the feasible domain is recorded by the int type Vis array, and the increment and decrement control the change of feasible region. because K can be less than N, recursive enumeration is required; note border control, due to improper border control WA many times.
It took a couple of hours to finally AC.
//Poj1321--dfs Backtracking#include <iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<algorithm>using namespacestd;Const intmaxn= -;Const intInf= (1<< -);intn,k;intMAP[MAXN][MAXN];intCNT;voidPutintXinty) { for(intI=1; i<=n;i++) {Map[i][y]++; Map[x][i]++; }}voidRemov (intXinty) { for(intI=1; i<=n;i++) {Map[i][y]--; Map[x][i]--; }}voidSearchintCurintnum) { for(intI=1; i<=n;i++){ if(Map[cur][i])Continue; BOOLflag=0; if(num==k) {CNT++; Flag=1;//The key to border control is here. You cannot return directly because the pieces you are placing are removed} put (cur,i); //Placing pieces if(!flag) { for(intj=cur+1; j<=n;j++) {Search (J,num+1); }} Remov (Cur,i); //Removing a pawn }}intMain () { while(cin>>n>>k,n!=-1, k!=-1){ for(intI=1; i<=n;i++){ for(intj=1; j<=n;j++){ CharCh;cin>>ch; if(ch=='#') map[i][j]=0; Elsemap[i][j]=1; }} CNT=0; for(intI=1; i<=n;i++) Search (i,1);//Recursive enumerationcout<<cnt<<Endl; } return 0;}
Poj1321_dfs Backtracking
Poj1321--dfs Backtracking