ACWING 844. Walking through the maze

Address: https://www.acwing.com/problem/content/846/

  Walk through the maze, from the upper left corner to the lower right corner, 0 can go, 1 can not go, ask at least a few steps.

  BFS solution: record the map through g [] [], and d [] [] is initialized to -1 to ensure that a point can only travel once and record the distance of each point to the end point.

  Note: Use the following statement to implement queue recording (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];     // The distance from each point to the starting point /// Do n’t walk 
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;
}

 

Guess you like

Origin www.cnblogs.com/liyexin/p/12680832.html