Maze Shortest Path---breadth First search (wide search)

Source: Internet
Author: User

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;
}

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.