【穿越栅栏】

农夫John在外面的田野上搭建了一个巨大的用栅栏围成的迷宫。幸运的是,他在迷宫的边界上留出了两段栅栏作为迷宫的出口。更幸运的是,他所建造的迷宫是一个“完美的”迷宫:即你能从迷宫中的任意一点找到一条走出迷宫的路。给定迷宫的宽W(1<=W<=38)及长H(1<=H<=100)。 2*H+1行,每行2*W+1的字符以下面给出的格式表示一个迷宫。然后计算从迷宫中最“糟糕”的那一个点走出迷宫所需的步数(就是从最“糟糕”的一点,走出迷宫的最少步数)。(即使从这一点以最优的方式走向最靠近的出口,它仍然需要最多的步数)当然了,牛们只会水平或垂直地在X或Y轴上移动,他们从来不走对角线。每移动到一个新的方格算作一步(包括移出迷宫的那一步)这是一个W=5,H=3的迷宫:

+-+-+-+-+-+
|         |
+-+ +-+ + +
|     | | |
+ +-+-+ + +
| |     |  
+-+ +-+-+-+

如上图的例子,栅栏的柱子只出现在奇数行或奇数列。每个迷宫只有两个出口。

格式
PROGRAM NAME: maze1

INPUT FORMAT:
(file maze1.in)

第一行: W和H(用空格隔开)

第二行至第2*H+2行: 每行2*W+1个字符表示迷宫

OUTPUT FORMAT:
(file maze1.out)

输出一个单独的整数,表示能保证牛从迷宫中任意一点走出迷宫的最小步数。

SAMPLE INPUT
5 3
+-+-+-+-+-+
|         |
+-+ +-+ + +
|     | | |
+ +-+-+ + +
| |     |  
+-+ +-+-+-+

SAMPLE OUTPUT
9

 

#include<iostream>
#include<cstring>
using namespace std;
int step[101][40];
char map[210][100];
int w,h,ans;
void floodfill(int x,int y,int dep)
{
    if (dep<step[x][y]) step[x][y]=dep;
    else return ;
    if (x>1 && map[2*x-1][2*y]==' ') floodfill(x-1,y,dep+1);
    if (x<h && map[2*x+1][2*y]==' ') floodfill(x+1,y,dep+1);
    if (y>1 && map[2*x][2*y-1]==' ') floodfill(x,y-1,dep+1);
    if (y<w && map[2*x][2*y+1]==' ') floodfill(x,y+1,dep+1);
}
void find_way()
{
    for (int i=1;i<=h;i++)
    {
        if (map[2*i][1]==' ') floodfill(i,1,1);
        if (map[2*i][2*w+1]==' ') floodfill(i,w,1);
    }
    
    for (int i=1;i<=w;i++)
    {
        if (map[1][2*i]==' ') floodfill(1,i,1);
        if (map[2*h+1][2*i]==' ') floodfill(h,i,1);
    }
}
int main()
{
    freopen("maze1.in","r",stdin);
    freopen("maze1.out","w",stdout);
    scanf("%d %d",&w,&h);getchar();
    for (int i=1;i<=2*h+1;i++)
    {
        for (int j=1;j<=2*w+1;j++)
            scanf("%c",&map[i][j]);
        getchar();
    }
    memset(step,127,sizeof(step));
    find_way();
    ans=0;
    for (int i=1;i<=h;i++)
        for (int j=1;j<=w;j++)
            if (ans<step[i][j]) ans=step[i][j];
    printf("%d\n",ans);
    return 0;
}

 

posted @ 2015-07-06 10:05  尹星寒  阅读(659)  评论(0编辑  收藏  举报