运用bfs算法
给你一个n行m列的二维迷宫。'S'表示起点,'T' 表示终点,'#' 表示墙壁,'.' 表示平地。你需要从 'S' 出发走到 'T',每次只能上下左右走动,并且不能走出地图的范围以及不能走到墙壁上。请你计算出走到终点需要走的最少步数。
输入格式
第一行输入n, m表示迷宫大小。(1≤n,m≤100)
接下来输入n行字符串表示迷宫,每个字符串长度为m。(地图保证有且仅有一个终点,一个起始点)
输出格式
输出走到终点的最少步数,如果不能走到终点输出−1,占一行。
样例输入1
2 3
S.#
..T
样例输出1
3
样例输入2
3 3
S.#
.#.
.#T
样例输出2
-1
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class point{
int x,y,step;
public point(int xx,int yy,int stepp){
x=xx;
y=yy;
step=stepp;
}
}
public class Main {
static int n,m,beginX,beginY,endX,endY;
static char[][] arry;
static int[][] brry;
public static int suanFa(int beginX,int beginY){
Queue<point> q = new LinkedList<point>();
q.add(new point(beginX,beginY,0));
brry[beginX][beginY]=1;
while(!q.isEmpty()){
point a = q.poll();
int x = a.x;
int y = a.y;
if(x==endX&&y==endY){
return a.step;
}
for(int i=0;i<4;i++){
if(x+1<n&&arry[x+1][y]!='#'&&brry[x+1][y]==0){brry[x+1][y]=1;q.add(new point(x+1,y,a.step+1));}
if(x-1>=0&&arry[x-1][y]!='#'&&brry[x-1][y]==0){brry[x-1][y]=1;q.add(new point(x-1,y,a.step+1));}
if(y+1<m&&arry[x][y+1]!='#'&&brry[x][y+1]==0){brry[x][y+1]=1;q.add(new point(x,y+1,a.step+1));}
if(y-1>=0&&arry[x][y-1]!='#'&&brry[x][y-1]==0){brry[x][y-1]=1;q.add(new point(x,y-1,a.step+1));}
}
}
return -1;
}
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
m = scan.nextInt();
arry = new char[n][m];
brry = new int[n][m];
for(int i=0;i<n;i++){
arry[i]=scan.next().toCharArray();
for(int j=0;j<m;j++){
if(arry[i][j]=='S'){beginX=i;beginY=j;}
if(arry[i][j]=='T'){endX=i;endY=j;}
}
}
System.out.println(suanFa(beginX,beginY));
}
}