搜索专题——迷宫寻宝

原题链接FZU—2285
题目描述
描述:洪尼玛今天准备去寻宝,在一个n*n (n行, n列)的迷宫中,存在着一个入口、一些墙壁以及一个宝藏。由于迷宫是四连通的,即在迷宫中的一个位置,只能走到与它直接相邻的其他四个位置(上、下、左、右)。现洪尼玛在迷宫的入口处,问他最少需要走几步才能拿到宝藏?若永远无法拿到宝藏,则输出-1。
输入:多组测试数据。每组数据输入第一行为正整数n,表示迷宫大小。接下来n行,每行包括n个字符,其中字符’.‘表示该位置为空地,字符’#'表示该位置为墙壁,字符’S’表示该位置为入口,字符’E’表示该位置为宝藏,输入数据中只有这四种字符,并且’S’和’E’仅出现一次。
n≤1000

输出:输出拿到宝藏最少需要走的步数,若永远无法拿到宝藏,则输出-1。
题目解法:模板题,广度优先搜索。
题目代码

#include<stdio.h>
#include<queue>
#include<math.h>
#include<string.h>
using namespace std;
char map[1000][1001];
int suit[1000][1001];
int n;
struct node
{
    int x,y;
    int step;
};
int check(int x,int y)
{
    if(x >= n || y >= n || map[x][y] == '#'||x<0||y<0||suit[x][y]==1)
        return 0;
    return 1;
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        int i,T=0;
        for(i=0;i<n;i++)
            scanf("%s",map[i]);
        memset(suit,0,sizeof(suit));
        struct node a,next;
        queue<node> Q;
        a.x=0,a.y=0;
        a.step=0;
        Q.push(a);
        while(!Q.empty())
        {
            a=Q.front();
            Q.pop();
            if(map[a.x][a.y]=='E')
            {
                printf("%d\n",a.step);
                T=1;
                break;
            }
            next.x=a.x-1;
            next.y=a.y;
            if(check(next.x,next.y))
            {
                next.step=a.step+1;
                suit[next.x][next.y]=1;
                Q.push(next);
            }
            next.x=a.x+1;
            next.y=a.y;
            if(check(next.x,next.y))
            {
                next.step=a.step+1;
                suit[next.x][next.y]=1;
                Q.push(next);
            }
            next.x=a.x;
            next.y=a.y+1;
            if(check(next.x,next.y))
            {
                next.step=a.step+1;
                suit[next.x][next.y]=1;
                Q.push(next);
            }
            next.x=a.x;
            next.y=a.y-1;
            if(check(next.x,next.y))
            {
                next.step=a.step+1;
                suit[next.x][next.y]=1;
                Q.push(next);
            }
        }
        if(T==0)
        printf("-1\n");
    }
    return 0;
}


欢迎留言哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值