The simplest introduction to BFS--the shortest path to the maze

Source: Internet
Author: User
the shortest path to the maze

Given a maze of size n*m. The maze is made up of channels and walls, each of which moves to the adjacent upper and lower left and right four-grid channels. Requests the minimum number of steps required from the start point to the end point. If you cannot reach it, the output "cannot go there". (n,m<=50, starting point, end point indicated by S,g respectively)

Input sample: N=5,m=5
#S # # # #
. ##.
#.###
.. ###
Output: 5

Analysis: This is a BFS template problem, direct demand for the shortest way, no other constraints
Here is the code

Simple BFS #include <cstdio> #include <iostream> #include <cstring> #include <queue> using
namespace Std;
Char maze[50][50];
BOOL VIS[10][10];
int n,m;
int sx,sy;
int Ex,ey;
    int dx[]={1,0,-1,0};//Four directions int dy[]={0,1,0,-1}; struct node {int x,y,step;}; void BFs () {node p;
    P.x=sx;p.y=sy;p.step=0;
    queue<node>q;
    Q.push (P);
    Vis[sx][sy]=1;
        while (!q.empty ()) {node Tmp=q.front ();
        Q.pop ();
                if (Tmp.x==ex&&tmp.y==ey) {cout<< "shortest circuit to" <<tmp.step<<endl;
        return;}
        for (int i=0;i<4;i++) {int xx=tmp.x+dx[i];
        int yy=tmp.y+dy[i]; if (maze[xx][yy]!= ' # ' &&xx>0&&yy>0&&xx<=n&&yy<=m&&!vis[xx][
            YY]) {node TP;
            Tp.x=xx;
            Tp.y=yy;
            tp.step=tmp.step+1;
            Vis[xx][yy]=1;
        Q.push (TP); }}} cout << "Can't go there.""<< Endl;} int main () {while (~scanf ("%d%d", &n,&m) &&n!=0&&m!=0) {memset (vis,0,sizeof (VIS));//Tag array
          Clear 0 for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) {cin>>maze[i][j];
            if (maze[i][j]== ' S ') {sx=i;sy=j;}


    if (maze[i][j]== ' G ') {ex=i;ey=j;}
    } BFS ();

 }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.