题目描述:
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 4x4) 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 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.
输出描述:
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
题意:
在国际象棋小棋盘(最多4x4)中可以包含车不能通过的墙。
求棋盘上最多可以放多少配置是合法的车
数据范围:
棋盘规模最多4x4
思路:
利用dfs搜索
从0辆车开始搜索
用一个全局变量来记录可放置的最多的车的数量
遍历整张图遇到可放置的格子就把这个格子标记上并进行下一次搜索同时车辆加一
在回溯时把该格子标记去掉。
代码:
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
char Map[6][6];
int visited[6][6];
int maxn,r,k;
bool place(int x,int y)
{
for(int i = x+1;i < k&&Map[i][y] != 'X';i++)//往右找
if(visited[i][y]) return false;
for(int i = x-1;i >= 0&&Map[i][y] != 'X';i--)//往左找
if(visited[i][y]) return false;
for(int i = y-1;i >= 0&&Map[x][i] != 'X';i--)//往上找
if(visited[x][i]) return false;
for(int i = y+1;i < k&&Map[x][i] != 'X';i++)//往下找
if(visited[x][i]) return false;
return true;
}
void placed(int r)
{
if(r > maxn) maxn = r;
for(int i = 0;i < k;i++)
for(int j = 0;j < k;j++)
if(!visited[i][j]&&Map[i][j] == '.'&&place(i,j))
{
visited[i][j] = 1;
placed(r+1);
visited[i][j] = 0;
}
}
int main()
{
while(cin >> k&&k)
{
maxn = 0;
memset(visited,0,sizeof(visited));
memset(Map,0,sizeof(Map));
for(int i=0;i<k;i++)
for(int j=0;j<k;j++)
cin>>Map[i][j];
placed(0);
cout << maxn << endl;
}
return 0;
}