2022河南萌新联赛第(四)场:G.迷宫(bfs)

题目描述
迷宫由墙和路组成,大Z需要从 (1,1)开始出发走到 (n,m),每走一步的时间是 1s,其中墙不能通过。

大Z发现在迷宫的路上长有神奇的花朵,吃了这种花朵可以让时间倒流 1s,每个花朵只能吃一次,且花朵状态不会跟随时间倒流。

现在大 Z 想让你计算他从 (1,1)走到 (n,m)所花费的时间。

'.' 表示路

'#' 表示墙

'*' 表示花朵

保证第一行第一个字符为 '.'

输出描述:
一个数字 表示大Z从 (1,1) 到 (n,m) 的最短时间,如果不能到达,输出 -1
示例1
输入
3 3
...
.*.
...
输出
3

示例2
输入
3 3
..#
.#.
#*.
输出
-1

一直找最小的就好了
习惯了写memset(dist,-1,sizeof dist);
)这种写法在更新的时候就极为麻烦

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
typedef long long LL;
const int N=200200,M=2002;
LL n,m,dist[M][M];
char a[M][M];
int dx[]={-1,0,0,1},dy[]={0,1,-1,0};
int bfs()
{
    queue<PII> q;
    memset(dist,0x3f3f3f3f,sizeof dist);//这里变成正无穷
    dist[1][1]=0;
    q.push({1,1});
    while(q.size())
    {
        auto t=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            int xx=dx[i]+t.first,yy=dy[i]+t.second;
            if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]!='#')
            {
                int flag=1;
                if(a[xx][yy]=='*') flag=0;
                if(dist[xx][yy]>dist[t.first][t.second]+flag)//这个地方不断的减少距离
                {
                    dist[xx][yy]=dist[t.first][t.second]+flag;
                    q.push({xx,yy});
                }
            }

        }
    }
    return dist[n][m];
}
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        cin>>a[i][j];
    bfs();
    /*for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            cout<<dist[i][j]<<" ";
        }
        cout<<endl;
    }*/
    if(dist[n][m]>=5000) cout<<"-1"<<endl;
    else cout<<dist[n][m]<<endl;
    return 0;
}
posted @ 2022-08-07 11:52  高尔赛凡尔娟  阅读(25)  评论(0编辑  收藏  举报