Ultraviolet A 639 Don't Get Rooked (brute force backtracking), 639 rooked
Ultraviolet A 639 Don't Get Rooked
In chess, the rook is a piece that can move any number of squares vertically or horizontally. in this problem we will consider small chess boards (at most 44) that can also contain Wils through which rooks cannot move. the goal is to place as your rooks on a board as possible so that no two can capture each other. A configuration of rooks isLegalProvided that no two rooks are on the same horizontal row or vertical column unless there is at least one wall separating them.
The following image shows five pictures of the same board. the first picture is the empty board, the second and third pictures show legal usages, and the fourth and every th pictures show illegal usages. for this board, the maximum number of rooks in a legal configuration is 5; the second picture shows one way to do it, but there are several other.
Your task is to write a program that, given a description of a board, calculates the maximum number of rooks that can be placed on the board in a legal configuration.
Input The input file contains one or more board descriptions, followed by a line containing the number 0 that signals the end of the file. Each board description begins with a line containing a positive integer
NThat is the size of the board;
NWill be at most 4. The next
NLines each describe one row of the board, with' .'Indicating an open space and an uppercase' X'Indicating a wall. there are no spaces in the input file. output For each test case, output one line containing the maximum number of rooks that can be placed on the board in a legal configuration. sample Input
4.X......XX......2XX.X3.X.X.X.X.3....XX.XX4................0
Sample Output
51524
How many cars can be placed on a board.
Solution: backtracking.
# Include <stdio. h> # include <string. h> int gra [8] [8], n, ans; int check (int x, int y) {for (int I = x + 1; I <= n & gra [I] [y]! = 0; I ++) {// if (gra [I] [y] =-1) return 0 ;}for (int I = x-1; i> = 1 & gra [I] [y]! = 0; I --) {// if (gra [I] [y] =-1) return 0;} for (int I = y + 1; I <= n & gra [x] [I]! = 0; I ++) {// right if (gra [x] [I] =-1) return 0 ;}for (int I = y-1; i> = 1 & gra [x] [I]! = 0; I --) {// left if (gra [x] [I] =-1) return 0;} return 1;} void DFS (int) {for (int I = 1; I <= n; I ++) {for (int j = 1; j <= n; j ++) {if (gra [I] [j] = 1 & check (I, j) {// can I place pawns, is it not relative to other pawns? gra [I] [j] =-1; DFS (a + 1); gra [I] [j] = 1 ;}}} if (ans <a) ans = a;} int main () {while (scanf ("% d", & n) = 1, n) {getchar (); char temp; memset (gra, 0, sizeof (gra); for (int I = 1; I <= n; I ++) {for (int j = 1; j <= n; j ++) {scanf ("% c", & temp); if (temp = '. ') gra [I] [j] = 1; else gra [I] [j] = 0;} getchar ();} ans = 0; DFS (0 ); printf ("% d \ n", ans);} return 0 ;}