POJ 1321 board problems (Search)
Time Limit:1000 MS |
|
Memory Limit:10000 K |
Total Submissions:28825 |
|
Accepted:14276 |
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
Sample Output
21
As a search question, there are two arrays dx [], dy [], which are used to search. In fact, they are used to walk through the maze ..
The question requires different rows and columns of the chess piece to be selected, so we can search one row and find it. # Then we can directly enter the next row.
In this way, different rows are guaranteed first, and then a vis [] array is opened to record the number of columns where the pawns are located. You can search them in depth.
[Source code]
# Include
# Include
# Include
Using namespace std; int n, k, ans; char map [10] [10]; bool vis [10]; void dfs (int cur, int cnt) {if (cnt = k) {ans ++; return;} if (cur> n) // if the last line is exceeded, return; for (; cur <= n; cur ++) // start from the first row to search for (int j = 1; j <= n; j ++) {if (map [cur] [j] = '#'&&! Vis [j]) {vis [j] = 1; dfs (cur + 1, cnt + 1); vis [j] = false; // backtracking }}int main () {while (scanf (% d, & n, & k )! = EOF & n! =-1 & k! =-1) {memset (vis, 0, sizeof (vis); for (int I = 1; I <= n; I ++) for (int j = 1; j <= n; j ++) {scanf (% c, & map [I] [j]);} ans = 0; dfs (1, 0); printf (% d, ans);} return 0 ;}