迷宫入门问题
原题
题目描述
小明置身于一个迷宫,请你帮小明找出从起点到终点的最短路程。 小明只能向上下左右四个方向移动。
输入
输入包含多组测试数据。输入的第一行是一个整数T,表示有T组测试数据。 每组输入的第一行是两个整数N和M(1<=N,M<=100)。 接下来N行,每行输入M个字符,每个字符表示迷宫中的一个小方格。 字符的含义如下: ‘S’:起点 ‘E’:终点 ‘-’:空地,可以通过 ‘#’:障碍,无法通过 输入数据保证有且仅有一个起点和终点。
输出
对于每组输入,输出从起点到终点的最短路程,如果不存在从起点到终点的路,则输出-1。
样例输入
5 5
s-###
-----
##---
E#---
---##
样例输出
9
#include
<iostream>
#include
<cstring>
#include
<string>
#include
<queue>
#include
<algorithm>
using namespace std
;
int de
[100][100];
char map
[100][100];
typedef pair
<int,int> P
;
int to
[2][4]={1,-1,0,0,0,0,1,-1};
int sx
,ex
,sy
,ey
;
int x
,y
,nx
,ny
;
int r
,l
;
int bfs()
{
memset(de
,-1,sizeof(de
));
queue
<P> qu
;
qu
.push(P(sx
,sy
));
de
[sx
][sy
]=0;
while(!qu
.empty())
{
P p
=qu
.front();
qu
.pop() ;
x
=p
.first
,y
=p
.second
;
if(x
==ex
&&y
==ey
) break;
for(int i
=0;i
<4;i
++)
{
nx
=x
+to
[0][i
];
ny
=y
+to
[1][i
];
if(nx
>=0&&nx
<r
&&ny
>=0&&ny
<l
&&map
[nx
][ny
]!='#'&&de
[nx
][ny
]==-1)
{
qu
.push(P(nx
,ny
));
de
[nx
][ny
]=de
[x
][y
]+1;
}
}
}
if(de
[ex
][ey
]==-1) return -1;
else return de
[ex
][ey
];
}
int main()
{
int n
,i
,j
;
while(cin
>>n
){
while(n
--){
cin
>>r
>>l
;
for(i
=0;i
<r
;i
++){
for(j
=0;j
<l
;j
++){
cin
>>map
[i
][j
];
if(map
[i
][j
]=='S')
{
sx
=i
,sy
=j
;
}
else if(map
[i
][j
]=='E')
{
ex
=i
,ey
=j
;
}
}
}
cout
<<bfs()<<endl
;
}
}
return 0;
}