UVa 639 Don't Get Rooked (DFS好题)

639 - Don't Get Rooked

Time limit: 3.000 seconds 

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=108&page=show_problem&problem=580

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.

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

使用-1表示墙,0表示没有车,1表示有车,使用dfs,注意换行遍历。


完整代码:

/*0.012s*/

#include<cstdio>
const int MAX = 10;

char map[MAX][MAX];
int vis[MAX][MAX], n;

bool ok_place(int i, int j)
{
	int left, up;
	///向左和向上查车
	for (left = j - 1; left >= 0; --left)
	{
		if (vis[i][left] == -1) break;
		if (vis[i][left]) return false;
	}
	for (up = i - 1; up >= 0; --up)
	{
		if (vis[up][j] == -1) break;
		if (vis[up][j]) return false;
	}
	return true;
}

int dfs(int i, int j)
{
	int count = 0, max = 0;
	while (i < n)
	{
		if (!vis[i][j] && vis[i][j] != -1 && ok_place(i, j))
		{
			vis[i][j] = 1;
			count = dfs(i, j + 1) + 1;
			if (count > max) max = count;
			vis[i][j] = 0;
		}
		if (j >= n - 1)
		{
			++i;
			j = 0;///换行~
		}
		else ++j;
	}
	return max;
}

int main()
{
	int i, j;
	while (scanf("%d\n", &n), n)
	{
		for (i = 0; i < n; ++i)
		{
			gets(map[i]);
			for (j = 0; j < n; ++j)
				vis[i][j] = (map[i][j] == 'X' ? -1 : 0);
		}
		printf("%d\n", dfs(0, 0));
	}
	return 0;
}

你可能感兴趣的:(C++,ACM,uva)