原题:
Suppose that we have a square city with straight streets. A map of a city is a square board with n rows and n columns, each representing a street or a piece of wall.
A blockhouse is a small castle that has four openings through which to shoot. The four openings are facing North, East, South, and West, respectively. There will be one machine gun shooting through each opening.
Here we assume that a bullet is so powerful that it can run across any distance and destroy a blockhouse on its way. On the other hand, a wall is so strongly built that can stop the bullets.
The goal is to place as many blockhouses in a city as possible so that no two can destroy each other. A configuration of blockhouses is legal provided that no two blockhouses are on the same horizontal row or vertical column in a map unless there is at least one wall separating them. In this problem we will consider small square cities (at most 4x4) that contain walls through which bullets cannot run through.
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 blockhouses 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 map, calculates the maximum number of blockhouses that can be placed in the city in a legal configuration.
题意:
在一个由方格组成的城镇中有一些墙,需要在空着的地方放一些碉堡,这些碉堡不能直接面对,也就是在同一列或同一行而且中间没有墙隔着,这样两个碉堡就会误伤,但是墙无比坚固所以可以阻碍攻击。给出这个城镇的墙的分布,问最多能够放多少个碉堡。
题解:
这个深搜难度就要比前边几个稍大一点,说白了是因为第一个碉堡不一定放在哪里,也就是起点不确定,所以要全部遍历一遍将从每个点开始深搜找出能放的碉堡的数量的最大值,但是在一次搜索中放过碉堡的地方就不必再次搜索。同时还要注意墙的问题,判断这个格子能否放碉堡的判据是不越界,不是墙,横竖两个方向不会碰到碉堡,也就是搜索横竖两个方向要么会搜出界,要么会搜到墙然后停止,如果搜到碉堡那这个位置则不能放。
代码:AC
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
char map[5][5];
char visit[5][5];
int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int n;
int sum;
void DFS(int ans)
{
int flag;
int i,j,k;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(map[i][j]=='.')
{
flag=0;
for(k=0;k<4;k++)
{
int dx=i+d[k][0];
int dy=j+d[k][1];
while(1)
{
if(dx<0||dy<0||dx>=n||dy>=n||map[dx][dy]=='X')
break;
if(map[dx][dy]=='1')
flag=1;
dx+=d[k][0];
dy+=d[k][1];
}
}
if(!flag)
{
map[i][j]='1';
DFS(ans+1);
map[i][j]='.';
}
}
}
}
if(sum<ans)
sum=ans;
}
int main()
{
while(cin>>n&&n)
{
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
cin>>map[i][j];
sum=0;
DFS(0);
cout<<sum<<endl;
}
return 0;
}