问题描述:
小明置身于一个迷宫,请你帮小明找出从起点到终点的最短路程。
小明只能向上下左右四个方向移动。
输入
输入包含多组测试数据。输入的第一行是一个整数T,表示有T组测试数据。
每组输入的第一行是两个整数N和M(1<=N,M<=100)。
接下来N行,每行输入M个字符,每个字符表示迷宫中的一个小方格。
字符的含义如下:
‘S’:起点
‘E’:终点
‘-’:空地,可以通过
‘#’:障碍,无法通过
输入数据保证有且仅有一个起点和终点。
输出
对于每组输入,输出从起点到终点的最短路程,如果不存在从起点到终点的路,则输出-1。
样例输入
样例输出
9
题目原文https://www.dotcpp.com/oj/problem1672.html
题解:
解题思想:广度优先搜索(BFS)
public class Main{
public static class Q{
int x;
int y;
int dept;//当前步数
}
static int[][] move = {{0,1},{0,-1},{1,0},{-1,0}};
static public void bfs(int[][] vis,int sx,int sy,LinkedList<Q> que,int gx,int gy,int n,int m,char[][] arr) {
Q q = new Q();
q.x = sx;
q.y = sy;
q.dept = 0;
que.add(q);//添加
int finish=0,result=0;
while(que.size() != 0) {
Q first = que.poll(); //取出对头,并删除
if(first.x == gx && first.y == gy) {
finish =1;
result = first.dept;
break;
}
for(int i=0 ; i< 4 ; i++) {
int tx = first.x + move[i][0];
int ty = first.y + move[i][1];
//边界判定和判定是否走过
if(tx >=0 && tx <n && ty>=0 && ty<m && arr[tx][ty]!='#' && vis[tx][ty]==0) {
vis[tx][ty] = 1;
Q temp = new Q();
temp.x = tx;
temp.y = ty;
temp.dept=first.dept+1;
que.add(temp);
}
}
}//while
//输出结果
if (result==0) {
System.out.println("-1");
}else {
System.out.println(result);
}
}
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int t = sc.nextInt();
while( t-- > 0 ) {
int n = sc.nextInt();
int m = sc.nextInt();
char[][] arr = new char[n][m];
int sx=0,sy=0;
int gx=0,gy=0;
int[][] vis = new int[n][m];
LinkedList<Q> que = new LinkedList<Q>();
//
for(int i=0 ; i < n ;i++) {
String str=sc.next();
for(int j=0 ; j< m ;j++) {
arr[i][j] = str.charAt(j);
if(arr[i][j] == 'S') {
sx=i;
sy=j;
}
if(arr[i][j] == 'E') {
gx=i;
gy=j;
}
}
}
vis[sx][sy]=1;//标记开始坐标
//广搜
bfs(vis,sx,sy,que,gx,gy,n,m,arr);
}//while
}
}