您的位置:首页 > 其它

UVA 639 Don't Get Rooked

2015-08-06 17:08 603 查看

分析

摆棋盘,但是只需要判断横纵有阻隔或者不能多个。所以只需要
回溯法
,先摆上再检查,如果不能这么摆再拿掉继续尝试。每完成一次棋盘取最大值即得到答案。

代码

#include <cstdio>
#define MAX_N 5

char G[MAX_N][MAX_N];
int N, max;

bool check(int x, int y)
{
int next[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
for (int i = 0; i < 4; i++) {
int dx = x + next[i][0];
int dy = y + next[i][1];
while (0 <= dx && dx < N && 0 <= dy && dy < N) {
if (G[dx][dy] == 'X') break;
if (G[dx][dy] == '*') return false;
dx += next[i][0];
dy += next[i][1];
}
}
return true;
}

void solve(int x, int y, int n)
{
for (int i = x; i < N; i++)
for (int j = 0; j < N; j++)
if (G[i][j] == '.' && check(i, j)) {
G[i][j] = '*';
solve(i, j, n+1);
G[i][j] = '.';
}
max = max < n ? n : max;
}

int main()
{
while (scanf("%d", &N), N) {
for (int i = 0; i < N; i++) scanf("%s", G[i]);
max = 0;
solve(0, 0, 0);
printf("%d\n", max);
}
return 0;
}


题目

Description

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 4×\times4) 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.

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 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.

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..
....
2
XX
.X
3
.X.
X.X
.X.
3
...
.XX
.XX
4
....
....
....
....
0


Sample Output

5
1
5
2
4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: