OpenJ_Bailian-3752 Walks the Labyrinth

Topic links http://bailian.openjudge.cn/practice/3752?lang=en_US

subject

A labyrinth consists of R rows and C rows. Some of the lattices have obstacles and can't walk. Some of the lattices are empty space and can walk.  
Given a labyrinth, find out how many steps it takes to walk from the upper left corner to the lower right corner at least (data guarantees it will). You can only walk horizontally or vertically, not obliquely.  

Input

The first line is two integers, R and C, representing the length and width of the maze. (1<= R, C<== 40)
Next is line R, each line of C characters, representing the entire maze.  
Space lattices are represented by'.', and barrier lattices are represented by''.  
The upper left corner and the lower right corner of the maze are'.'.

Output

How many steps (i.e. how many empty spaces) does it take to get the output from the upper left corner to the lower right corner? The calculation steps should include the starting point and the end point.

Sample Input

5 5
..###
#....
#.#.#
#.#.#
#.#..

Sample Output

9

Thoughts on BFS Classic Topics

AC code

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<string>
#include<utility>
using namespace std;
const int inf=1000000;
char maps[105][105];
int d[105][105];
typedef pair < int,int > P;
int n,m;
int move1[5]={-1,0,1,0};
int move2[5]={0,1,0,-1};
int bfs()
{   queue<P> q;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
          d[i][j]=inf;
    q.push(P(0,0));
    d[0][0]=1;
    while(q.size()){
         P p;
         p=q.front();
         q.pop();
        if(p.first==n-1&&p.second==m-1)
            break;
        for(int i=0;i<4;i++){
            int x=p.first+move1[i];
            int y=p.second+move2[i];
            if(x>=0&&x<n&&y>=0&&y<m&&d[x][y]==inf&&maps[x][y]!='#'){
                q.push(P(x,y));
                d[x][y]=d[p.first][p.second]+1;
            }
        }

    }
    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>>maps[i][j];
    cout<<bfs()<<endl;
    return 0;
}

Posted by tdelobe on Sun, 24 Mar 2019 06:00:28 -0700