您的位置:首页 > 其它

zoj 1002 Fire Net (DFS搜索)

2013-04-22 21:17 281 查看
1002 Fire Net

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

// File Name: Fire Net 1002.cpp
// Author: sheng
// Created Time: 2013年04月22日 星期一 17时07分28秒

#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;

const int maxn = 5;
int m_ans, n;
char map[maxn][maxn];

bool Build (int row, int col)
{
int i;
for (i = row; i >= 0; i --)//检查之前的状态
{
if (map[i][col] == 'O') // 表明在这一列已经存在一个碉堡了 && 中间没有墙
return false;
if (map[i][col] == 'X') // 表明这一列中间有一堵墙,说明可以放个碉堡
break;
}
for (i = col; i >= 0; i --)    //同上
{
if (map[row][i] == 'O')
return false;
if (map[row][i] == 'X')
break;
}
return true;
}

void Dfs(int s, int ans)
{
int row, col;
if (s == n * n)
{
if (ans > m_ans)
m_ans = ans;
return;
}
row = s/n;
col = s%n;
if (map[row][col] == '.' && Build (row, col))
{
map[row][col] = 'O';
Dfs (s+1, ans + 1);
map[row][col] = '.'; //使用完之后还原继续递归
}
Dfs (s+1, ans);
}

int main()
{
while (scanf ("%d", &n) && n)
{
m_ans = 0;
for (int i = 0; i < n; i ++)
scanf ("%s", map[i]);
Dfs(0, 0);
printf ("%d\n", m_ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: