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