POJ 1321-board problem (DFS recursion), poj1321-
POJ 1321-board problem K-DFSTime Limit:1000 MSMemory Limit:10000KB64bit IO Format:% I64d & % I64u
Description
There is no difference in placing a piece on a given-shape chessboard (which may be irregular. It is required that any two pawns should not be placed in the same row or column of the board. Please program to solve all feasible placement schemes C for all k pawns with a given shape and size.
Input
The input contains multiple groups of test data.
The first row of each group of data is two positive integers, n k, separated by a space, indicating that the board will be described in an n * n matrix, and the number of pieces placed. N <= 8, k <= n
If it is-1-1, the input ends.
The next n lines describe the shape of the Board: each line has n characters, where # indicates the board area, and .. indicates the blank area (no extra blank rows or columns are required for data ).
Output
For each group of data, a single line of output is provided, and the number of solutions placed in the output is C (Data guarantee is C <2 ^ 31 ).
Sample Input
2 1 #... #4 4... #-1-1
Question: at the first glance, I thought the problem was very similar to that of Queen n. Let's take a closer look at it. The method is the same. Recursive thinking is the same, this article only requires that the position of the pawns should be specified as long as the judgment is not in one row or column, so the judgment conditions should be added.
Let's take a look at Queen n's question first.
DFS Recursion
# Include <iostream> # include <cstdio> # include <cstring> using namespace std; char a [10] [10]; // record the Board position int book [10]; // record whether a piece has been removed int n, k; int total, m; // total indicates the number of pieces to be placed, m is the number of chess pieces that have been placed into the board void DFS (int cur) {if (k = m) {total ++; return ;}if (cur> = n) // Boundary
Return; for (int j = 0; j <n; j ++) if (book [j] = 0 & a [cur] [j] = '#') // judgment condition {book [j] = 1; // mark m ++; DFS (cur + 1); book [j] = 0; // change back to facilitate the next row's judgment m --;} DFS (cur + 1); // to the next line} int main () {int I, j; while (scanf ("% d", & n, & k) & n! =-1 & k! =-1) // constraints {total = 0; m = 0; for (I = 0; I <n; I ++) scanf ("% s ", & a [I]); memset (book, 0, sizeof (book); DFS (0); printf ("% d \ n", total );} return 0 ;}