BFS: Finding the shortest path length

Source: Internet
Author: User

<title>BFS: Finding the shortest path length</title> BFS: Finding the shortest path length

Title: Shortest path to the maze
Given a maze of size n x M. The maze consists of passages and walls. Each step can be adjacent to the upper and lower left and right four-grid channel
Move. Request the minimum number of steps required from the start point to the end point

#S ######.#......#. #.#.##.##.#.#........##.##.####....#....#.#######.#.#######.#....#......####.###.....#... g#
Output 22
#include <cstdio>#include <queue>using namespace STD;Const int inf= 0X3FFFFFFF;Const int MAXN= 105;Char g[MAXN] [MAXN];int SX,Sy;int GX,Gy;int N;int m;int D[MAXN] [MAXN];int BFS() {Queue<pair<int,int> >que; for(int I= 0; I < n; i++) { for(int J= 0; J < M;        J + +) {D[i][j] = inf;    }} que.push (Make_pair (SX, SY)); D[sx][sy] = 0; while(Que.size ()) {pair<int,int>P= Que.front (); Que.pop ();if(P.first = = GX && P.second = = gy) { Break; }int DX[4] = {1, 0,-1, 0};int Dy[4] = {0, 1, 0,-1}; for(int I= 0; I < 4; i++) {int NX= P.first + dx[i];int NY= P.second + dy[i];if(0 <= NX && NX < n && 0 <= ny && NY < M && G[nx][ny]! =' # '&& D[nx][ny] = = inf) {Que.push (Make_pair (NX, NY));            D[nx][ny] = D[p.first][p.second] + 1; }        }    }returnD[gx][gy];}void Solve() {int Res= BFS (); printf"%d\n", res);}int Main(void) {scanf ("%d%d", &n, &m); for(int I= 0; I < n; i++) { for(int J= 0; J < M; J + +) {scanf ("%c", &g[i][j]);// If the timeout can be considered with scanf ("%s", G[i]);            if(G[i][j] = =' S ') {SX = i;            sy = j; }Else if(G[i][j] = =' G ') {GX = i;            GY = j;    }} getchar (); } solve ();return0;}

BFS: Finding the shortest path length

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.