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.
4 .X.. .... XX.. .... 2 XX .X 3 .X. X.X .X. 3 ... .XX .XX 4 .... .... .... .... 0
5 1 5 2 4
这个也是简单的DFS,但是和之前写的几个方法上略有不同,由于开始想的太复杂了,所以导致陷入了一个误区,看了一个题解后,感觉还是很简单的(开始用结构体设置了visited属性标志着这个点是否走过,后来发现不用就去掉了,但是结构体还留着没删)。
#include<iostream>
#include<string>
#include<cstring>
#include<stdio.h>
#include<algorithm>
#include<cmath>
using namespace std;
int account,n;
struct Nod{
char str;
} array[5][5];
bool judge(int count)
{
int x = count / n;
int y = count % n;
int i;
for(i = y;i >= 0;i--)
{
if(array[x][i].str == 'X')
break;
if(array[x][i].str == '@')
return false;
}
for(i = x;i >= 0;i--)
{
if(array[i][y].str == 'X')
break;
if(array[i][y].str == '@')
return false;
}
return true;
}
void DFS(int count,int turn)
{
if(n * n == turn)
{
account = max(count,account);
return;
}
if(array[turn/n][turn%n].str == '.'&&judge(turn))
{
array[turn/n][turn%n].str = '@';
DFS(count+1,turn+1);
array[turn/n][turn%n].str = '.';
}
DFS(count,turn+1);
}
int main()
{
int i,j;
while(~scanf("%d",&n))
{
account = 0;
if(n == 0)
break;
for(i = 0;i < n;i++)
{
for(j = 0;j < n;j++)
{
cin>>array[i][j].str;
}
}
DFS(0,0);
cout<<account<<endl;
}
return 0;
}