![](https://img-blog.csdn.net/20150314110506985?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbHVja2lseXdt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
![](https://img-blog.csdn.net/20150314110635922?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbHVja2lseXdt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
#include<stdio.h>
#include<string.h>
#include<algorithm>
using
namespace
std;
struct
node
{
int
x,y;
int
step;
int
pre;
};
struct
queue
{
node a[10010];
int
front,rear;
}q;
#define N 110
int
n,m;
int
sx,sy;
int
vis[N][N];
char
mpt[N][N];
int
dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
void
show(
int
now)
{
int
path[10000],len=0;
while
(q.a[now].pre!=-1)
{
path[++len]=now;
now=q.a[now].pre;
}
for
(
int
i=len;i>=1;i--)
{
printf
(
"%d %d %d\n"
,q.a[path[i]].x,q.a[path[i]].y,q.a[path[i]].step);
}
}
void
bfs()
{
q.front=q.rear=0;
node now,next;
now.x=sx;
now.y=sy;
now.step=0;
now.pre=-1;
vis[now.x][now.y]=1;
q.a[++q.rear]=now;
while
(q.front!=q.rear)
{
now=q.a[++q.front];
if
(mpt[now.x][now.y]==
'E'
)
{
printf
(
"%d\n"
,now.step);
// show(q.front);
return
;
}
for
(
int
i=0;i<4;i++)
{
next=now;
next.step++;
next.x+=dir[i][0];
next.y+=dir[i][1];
if
(next.x>=1 && next.x<=n && next.y>=1 && next.y<=m && mpt[next.x][next.y]!=
'#'
&& !vis[next.x][next.y])
{
vis[next.x][next.y]=1;
next.pre=q.front;
q.a[++q.rear]=next;
}
}
}
printf
(
"-1\n"
);
}
int
main()
{
int
T,i,j;
scanf
(
"%d"
,&T);
while
(T--)
{
memset
(vis,0,
sizeof
(vis));
scanf
(
"%d%d"
,&n,&m);
for
(i=1;i<=n;i++)
{
for
(j=1;j<=m;j++)
{
scanf
(
" %c"
,&mpt[i][j]);
if
(mpt[i][j]==
'S'
)
{
sx=i;
sy=j;
}
}
}
bfs();
}
return
0;
}
本题与之上的第一题一样,也可以用深搜,但这样展示的是广搜。广搜最重要的,还是要建立队列,把每一步能走到的位置加入队列,千万不要忘记,
每一次扩展结束,要把front出队。这样才能继续扩展下去。