Question link: http://uva.onlinejudge.org/index.php? Option = com_onlinejudge & Itemid = 8 & page = show_problem & problem = 2136
Problem aAnother N-Queen Problem
I guessN-Queen problem is known by every person who has studied backtracking. In this problem you shoshould count the number of placementNQueens onN*NBoard so that no two queens attack each other. To make the problem a little bit harder (easier ?), There are some bad squares where queens cannot be placed. Please keep in mind that bad squares cannot be used to block queens 'attack.
Even if two solutions become the same after some rotations and reflections ctions, they are regarded as different. So there are exactly 92 solutions to the traditional 8-queen problem.
Inputthe input consists of at most 10 test cases. Each case contains one Integers
N(3 <
N<15) in the first line. The following
NLines represent the Board, where empty squares are represented by dots '. ', bad squares are represented by asterisks '*'. the last case is followed by a single zero, which shoshould not be processed. outputfor each test case, print the case number and the number of solutions. sample Input
8................................................................4.*..............0
Output for the sample input
Case 1: 92Case 2: 1
Rujia Liu's present 1: A tiny contest of Brute Force
After N, the enhanced version of the problem will time out when a common rollback occurs, so it is optimized using state compression and bit operations.
# Include <iostream> # include <cstring> # include <cstdio> # include <cmath> # include <algorithm> # include <vector> using namespace STD; const int max = 20; int STR [Max]; // The original string int N, MSK; char s [Max]; // The original string int DFS (int dep, int Dow, int lefd, int rigd) {// Dow, lefd, rigd: If (DEP> = N) return 1; int cur = ~ (STR [Dep] | Dow | lefd | rigd); // if the result is reversed, 1 indicates this layer, where it can be placed, and 0 indicates that this layer cannot be placed. Int P = cur & (-cur) & MSK; // get the last non-0 int ret = 0; while (p) {RET + = DFS (DEP + 1, dow | P, (lefd | P) <1, (rigd | P)> 1); cur ^ = P; // The position 0 p = cur & (-cur) & MSK;} return ret;} int main () {int CAS = 0; while (scanf ("% d ", & N), n) {MSK = (1 <n)-1; for (INT I = 0; I <n; I ++) {scanf ("% s", S); STR [I] = 0; For (Int J = 0; s [J]; j ++) {If (s [J] = '*') {STR [I] | = (1 <j ); // mark the inaccessible area as 1 }}printf ("case % d: % d \ n", ++ cas, DFS ));} return 0 ;}