Given an n∗m chessboard with some marked squares, your task was
to place as few queens as possible to guard (attack or occupy) all
marked squares. Below is a solution to an 8∗8 board with every
square marked. Note that Queens can is placed on non-marked
squares.
Input
The input consists in the most of the test cases. Each case begins with
a line containing the integers n, m (1 < N, m < ten) the size of
the chessboard. Next n lines each contain m characters, ' X ' denotes
marked square, '. ' Denotes unmarked squares. The last case was
followed by a single zero, and which should not being processed.
Output
For each test case, print the case number and the minimal number of Queens needed.
Sample Input
8 8
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
8 8
X ...
. X......
.. X.....
... X....
.... X...
..... X..
... X.
..... X
0
Sample Output
Case 1:5
Case 2:1
1#include <iostream>2#include <cstdio>3#include <cstring>4 5 using namespacestd;6 7 intn,m,maxd,cas=0, vis[Ten][ -];8 Chars[ the][ the];9 Ten BOOLDfsintCurintR) One { A if(cur==Maxd) - { - for(intI=1; i<=n;i++) the { - for(intj=1; j<=m;j++) - if(s[i][j]=='X'&&!vis[0][i]&&!vis[1][j]&&!vis[2][i+j]&&!vis[3][i-j+ One])///Judging whether this point is occupied - return false; + } - return true; + } A at for(inti=r;i<=n;i++) - { - for(intj=1; j<=m;j++) - { - if(!vis[0][i]| |! vis[1][j]| |! vis[2][i+j]| |! vis[3][i-j+ One])///row and column positive - { in intv1=vis[0][i],v2=vis[1][j],v3=vis[2][i+j],v4=vis[3][i-j+ One]; -vis[0][i]=vis[1][j]=vis[2][i+j]=vis[3][i-j+ One]=1;///Modifying global variables to if(Dfs (cur+1, i+1)) + return true; -vis[0][I]=V1;///change it back . thevis[1][j]=v2; *vis[2][i+j]=v3; $vis[3][i-j+ One]=v4;Panax Notoginseng } - } the } + return false; A } the + intMain () - { $ while(~SCANF ("%d", &n) &&N) $ { -scanf"%d",&m); - for(intI=1; i<=n;i++) thescanf"%s", s[i]+1); - Wuyi for(maxd=1;maxd<5; maxd++)///maximum of 5 queens the { -memset (Vis,0,sizeof(Vis)); Wu if(Dfs (0,0)) - Break; About } $printf"Case %d:%d\n",++cas,maxd); - } - return 0; -}
Attached, eight Queens question key code for easy comparison
memset (Vis,0,sizeof(Vis));voidSearch_ (intcur) { if(cur==n)///recursive boundarytot++; Else { for(intI=0; i<n;i++) { if(!vis[0][i]&&!vis[1][cur+i]&&!vis[2][cur-i+n])///column, sub-diagonal, main diagonal{C[cur]=i;///can print out its locationvis[0][i]=vis[1][cur+i]==vis[2][cur-i+n]=1;///Modify global variables so that recursionSearch_ (cur+1); vis[0][i]=vis[1][cur+i]=vis[2][cur-i+n]=0;///remember, to change back, the bottom is not based on the recursion above } } }}
Guarding the Chessboard