UV 11214 Guarding the Chessboard, 11214 chessboard
Question:
The Queen's defense scope is the horizontal, vertical, and diagonal lines where he is located. The # on the map is the place where the flag can be placed. Ask at least a few queens to defend all #.
Analysis:
The vis array has four dimensions, corresponding to rows, columns, primary diagonal lines, and secondary diagonal lines.
Code:
# Include <iostream>
# Include <cstring>
# Include <cstdio>
# Include <algorithm>
Using namespace std;
Int map [15] [15];
Int vis [4] [30];
Int n, m;
Int maxn;
Int kase;
Int same () // determines whether it can defend all #
{
Int I, j, k;
For (I = 0; I <n; I ++)
For (j = 0; j <m; j ++)
If (map [I] [j] &! Vis [0] [I] &! Vis [1] [j] &! Vis [2] [I + j] &! Vis [3] [n + j-I])
Return 0;
Return 1;
}
Int dfs (int d, int cur, int l) // d indicates the number of Queens, cur indicates the Queen is placed there, cur/m indicates the abscissa, and cur % m indicates the ordinate, l represents a total of several queens.
{
Int I, j, k;
If (d = l)
{
If (same ())
{
Printf ("Case % d: % d \ n", ++ kase, d );
Return 1;
}
Return 0;
}
Else
{
For (I = cur; I <n * m; I ++)
{
Int x = I/m, y = I % m;
Int tmp1 = vis [0] [x], tmp2 = vis [1] [y], tmp3 = vis [2] [x + y], tmp4 = vis [3] [n-x + y];
Vis [0] [x] = vis [1] [y] = vis [2] [x + y] = vis [3] [n-x + y] = 1;
If (dfs (d + 1, I, l ))
Return 1;
Vis [0] [x] = tmp1, vis [1] [y] = tmp2, vis [2] [x + y] = tmp3, vis [3] [n-x + y] = tmp4;
}
}
Return 0;
}
Int main ()
{
Kase = 0;
While (scanf ("% d", & n), n)
{
Scanf ("% d", & m );
Int I, j;
Memset (vis, 0, sizeof (vis ));
Memset (map, 0, sizeof (map ));
String s;
For (I = 0; I <n; I ++)
{
Cin> s;
For (j = 0; j <m; j ++)
{
If (s [j] = 'X ')
Map [I] [j] = 1;
}
}
For (maxn = 0; maxn ++)
{
Memset (vis, 0, sizeof (vis ));
If (dfs (0, 0, maxn ))
{
Break;
}
}
}
}