zoukankan      html  css  js  c++  java
  • ACWING 844.走迷宫

    地址:https://www.acwing.com/problem/content/846/

      走迷宫,从左上角走到右下角,0可走,1不可走,问最少需要几步。

      BFS解法:  通过g[][]记录地图,d[][]初始化为-1用来保证一个点只能走一次以及记录每个点到达终点的距离。

      注意:使用以下语句来实现队列记录(x,y);

    #include<queue>
    typedef pair<int,int>pp;
    queue<int>q;
    q.push({1,2});
    pp t=q.front;
    那么:t.first=1,t.second=2
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<queue>
    using namespace std;
    typedef pair<int,int>P; //!!!
    const int maxn = 105;
    int n,m;
    int g[maxn][maxn];
    int d[maxn][maxn];    //每个点到起点的距离 //没有走过 
    int dx[]={0,0,-1,1};
    int dy[]={1,-1,0,0};
    int bfs()
    {
        queue<P>q;
        memset(d,-1,sizeof(d));
        d[0][0]=0;
        q.push({0,0});
        while(!q.empty())
        {
            P t = q.front();
            q.pop();
            for(int i=0;i<4;i++)
            {
                int x=dx[i]+t.first;
                int y=dy[i]+t.second;
                if(x>=0&&y>=0&&x<n&&y<m&&g[x][y]==0&&d[x][y]==-1)
                {
                    d[x][y]=d[t.first][t.second]+1;
                    q.push({x,y});
                }
            }
        }
        return d[n-1][m-1];
    }
    int main()
    {
        cin>>n>>m;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                cin>>g[i][j];
        cout<<bfs()<<endl;
        return 0;
    }
  • 相关阅读:
    python10.31
    python10.29
    python10.28
    python10.27
    python10.25
    python10.24
    python10.23
    四边形不等式与决策单调
    0x57~0x59
    0x55~0x56
  • 原文地址:https://www.cnblogs.com/liyexin/p/12680832.html
Copyright © 2011-2022 走看看