您的位置:首页 > 其它

ZOJ 1002 Fire Net(DFS)

2013-03-27 13:49 435 查看
Fire NetTime Limit: 2 Seconds Memory Limit: 65536 KB
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.

View Code

# include<stdio.h>
# define max 4
char map[max][max];
int ibest,n;
bool canput(int row,int col){
int i;
for(i=row-1;i>=0;i--){
if(map[i][col]=='O') return false;
if(map[i][col]=='X') break;
}
for(i=col-1;i>=0;i--){
if(map[row][i]=='O')  return false;
if(map[row][i]=='X')   break;
}
return true;
}
void solve(int k,int current){
int x,y;
if(k==n*n){
if(current>ibest){
ibest=current; return ;
}
}
else{
x=k/n;
y=k%n;
if(map[x][y]=='.'&&canput(x,y)){
map[x][y]='O';
solve(k+1,current+1);
map[x][y]='.';
}
solve(k+1,current);
}
}
int main(){
int i,j;
char s[max];
while(scanf("%d",&n)&&n){
for(i=0;i<n;i++){
scanf("%s",s);
for(j=0;j<n;j++)
map[i][j]=s[j];
}
ibest=0;
solve(0,0);
printf("%d\n",ibest);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: