11214-Guarding the Chessboard (Brute Force Search)
IDA * algorithm, from small to large enumeration depth limit, but this question has a depth limit. The first example in the question shows that up to five queens can cover the entire board.
Using the techniques in zishu, we can quickly determine whether any two pieces are in the same row, the same column, and the same diagonal line (for details, see the two figures in zishu P193 ).
In this way, you can perform a brute-force search. Each layer requires O (nm) complexity, but it does not actually need that much complexity. Similar to the eight queens problem, the current row has already been placed in the Queen's, so you don't have to worry about it. It is good to place it from the next row each time.
For details, see the code:
# Include
Using namespace std; int n, m, maxd, kase = 0, vis [10] [30]; char s [15] [15]; bool dfs (int cur, int r) {if (cur = maxd) {for (int I = 1; I <= n; I ++) {for (int j = 1; j <= m; j ++) if (s [I] [j] = 'X '&&! Vis [0] [I] &! Vis [1] [j] &! Vis [2] [I + j] &! Vis [3] [I-j + 11]) return false;} return true;} for (int I = r; I <= n; I ++) {for (int j = 1; j <= m; j ++) {if (! Vis [0] [I] |! Vis [1] [j] |! Vis [2] [I + j] |! Vis [3] [I-j + 11]) {int v1 = vis [0] [I], v2 = vis [1] [j], v3 = vis [2] [I + j], v4 = vis [3] [I-j + 11]; // note, make sure to restore "original" vis [0] [I] = vis [1] [j] = vis [2] [I + j] = vis [3] [I-j + 11] = 1; if (dfs (cur + 1, I + 1) return true; vis [0] [I] = v1; vis [1] [j] = v2; vis [2] [I + j] = v3; vis [3] [I-j + 11] = v4 ;}} return false;} int main () {while (~ Scanf (% d, & n) {scanf (% d, & m); for (int I = 1; I <= n; I ++) scanf (% s, s [I] + 1); for (maxd = 1; maxd <5; ++ maxd) {memset (vis, 0, sizeof (vis )); if (dfs (0, 0) break;} printf (Case % d: % d, ++ kase, maxd);} return 0 ;}