迷宫plus(广搜+队列)

题目描述

给定n*m的迷宫 (2<n,m<24) ,迷宫中'0'代表路,'1'代表墙,'2'代表起点,'3'代表终点,求起点到终点最短距离

输入

多实例测试
第一行输入n,m
下面是n行,每行输入m个字符

输出

输出起点到终点最短距离

 

样例输入

5 3
0 0 0
0 1 0
0 2 0
0 1 3
0 0 0

样例输出

2

代码: 

//#include<bits/stdc++.h>   万能头文件

#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>

using namespace std;
char ma[205][205];
int dir[][2] = { 1,0,-1,0,0,1,0,-1 };
int n, m;
struct ff
{
    int x, y, time;
    friend bool operator<(ff n1, ff n2)
    {
        return n2.time < n1.time;
    }
} p, s, t;
void bfs(int a, int b)
{
    priority_queue<ff>q;
    p.x = a, p.y = b, p.time = 0;
    q.push(p);
    while (!q.empty())
    {
        s = q.top();
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            t.x = s.x + dir[i][0];
            t.y = s.y + dir[i][1];
            if (t.x >= 0 && t.x < n&&t.y >= 0 && t.y < m&&ma[t.x][t.y]!='1')
            {
                if (ma[t.x][t.y] == '3')
                {
                    printf("%d\n", s.time + 1);
                    return;
                }
                if (ma[t.x][t.y] == '0')
                {
                    t.time = s.time + 1;
                }
                q.push(t);
                ma[t.x][t.y] = '1';
            }
        }
    }
}

int main()
{
    int xx, yy;
    while (~scanf("%d%d", &n, &m))
    {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                cin >> ma[i][j];
                if (ma[i][j] == '2')
                {
                    xx = i;
                    yy = j;
                }
            }
        }
        bfs(xx, yy);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值