<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