This topic is more classic:
Input n,m, the length and width of the maze, find the shortest path from the starting point to the end point
Code:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#define MAXN 10
using namespace Std;
const int INF = 100000000;
When the class that represents the state is pair, the first typedef will be convenient
typedef pair<int,int> P;
Char MAZE[MAXN][MAXN];
int n,m;
int sx,sy;
int gx,gy;
int D[MAXN][MAXN];
Can move in four directions, down, left, right
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int BFS ()
{
Queue<p> que;
Class
for (int i=0;i<n;i++)
{
for (int j=0;j<m;j++)
{
D[i][j]=inf;
}
}
Place the starting point in the queue and set the default distance of the point to 0
Que.push (P (Sx,sy));
d[sx][sy]=0;
Search
while (Que.size ())
{
Remove front-end data from queues
P P=que.front ();
Que.pop ();
Determine whether to the boundary
if (P.FIRST==GX && p.second==gy)
Break
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 && Maze[nx][ny]!= ' # ' && D [NX] [NY] = = INF)
{
Que.push (P (Nx,ny));
d[nx][ny]=d[p.first][p.second]+1;
}
}
}
return d[gx][gy];
}
int main ()
{
scanf ("%d%d", &n,&m);
for (int i=0;i<n;i++)
{
for (int j=0;j<m;j++)
{
scanf ("%c", &maze[i][j]);
}
}
int Res=bfs ();
printf ("%d\n", res);
return 0;
}