标签:des style blog http io ar color os sp
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 walls through which rooks cannot move. The goal is to place as many rooks on a board as possible so that no two can capture each other. A configuration of rooks is legal provided 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 configurations, and the fourth and fifth pictures show illegal configurations. 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 ways.
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.
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 n that is the size of the board; n will be at most 4. The next n lines each describe one row of the board, with a `.‘ indicating an open space and an uppercase `X‘ indicating a wall. There are no spaces in the input file.
For each test case, output one line containing the maximum number of rooks that can be placed on the board in a legal configuration.
4 .X.. .... XX.. .... 2 XX .X 3 .X. X.X .X. 3 ... .XX .XX 4 .... .... .... .... 0
5 1 5 2 4
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <vector> 5 6 using namespace std; 7 8 string str[10]; 9 int visit[10][10]; 10 int n,ans; 11 int maxn = 0; 12 13 int ok (int x,int y) { 14 int Ok = 1; 15 for (int j = 0;j < n;j++) { 16 if (visit[x][j] == -1) { 17 Ok = 0; 18 for (int i = min(j,y) + 1;i < max(j,y);i++) { 19 if (str[x][i] == ‘X‘) { 20 Ok = 1; 21 break; 22 } 23 } 24 } 25 } 26 if (Ok) 27 for (int i = 0;i < n;i++) { 28 if (visit[i][y] == -1) { 29 Ok = 0; 30 for (int j = min(i,x) + 1;j < max(i,x);j++) { 31 if (str[j][y] == ‘X‘) { 32 Ok = 1; 33 break; 34 } 35 } 36 } 37 } 38 return Ok; 39 } 40 41 int dfs(int x,int y) { 42 for (int i = x;i < n;i++) { 43 for (int j = 0;j < n;j++) { 44 if (str[i][j] == ‘.‘ && visit[i][j] != -1 && ok(i,j)) { 45 visit[i][j] = -1; 46 ans ++; 47 if (ans > maxn) { 48 maxn = ans; 49 } 50 dfs(i,j); 51 visit[i][j] = 0; 52 ans --; 53 } 54 } 55 } 56 } 57 58 int main () { 59 // freopen("1.in","r",stdin); 60 while (cin >> n,n) { 61 getchar(); 62 for (int i = 0;i < n;i++) { 63 cin >> str[i]; 64 } 65 memset(visit,0,sizeof(visit)); 66 maxn = 0; 67 ans = 0; 68 dfs(0,0); 69 cout << maxn << endl; 70 } 71 }
标签:des style blog http io ar color os sp
原文地址:http://www.cnblogs.com/xiaoshanshan/p/4128193.html