package lanqiaobei;
import java.util.*;
/*
习题:走迷宫2
给你一个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
*/
public class ZouMIGong_bfs {
public static List<point> a = new ArrayList<>();
static point up = new point(0, 1);
static point down = new point(0, -1);
static point left = new point(-1, 0);
static point right = new point(1, 0);
public static int ress = -1;
public static void bfs(int sx, int sy, char[][] dt) {
// (sx, sy)为搜索的起点
//res存放sx,sy到循环的当前nx,ny的步数
int[][] res = new int[dt.length][dt[0].length];
a.add(up);
a.add(down);
a.add(left);
a.add(right);
//队列来进行while循环进行层搜索用的
Queue<point> q = new LinkedList();
((LinkedList) q).add(new point(sx, sy));
//一层一层的搜索bfs
while (!q.isEmpty()) {
//获取并移除当前对列队头的元素并赋值
point newp = q.poll();
int x = newp.x;
int y = newp.y;
//只能向上下左右四个方向进行移动
for (int i = 0; i < a.size(); i++) {
point sum = a.get(i);
int nx = x + sum.x;
int ny = y + sum.y;
//判断是否在当前的界限内
if (nx >= 0 && nx < dt.length && ny >= 0 && ny < dt[0].length) {
//判断是否能到达
if (dt[nx][ny] != '#' && dt[nx][ny] != '!') {
//判断当前层中是否有能到达T的,是否结束
if (dt[nx][ny] == 'T') {
ress = res[x][y] + 1;
return;
} else {
//设置上标志位
dt[nx][ny] = '!';
//从x,y到nx,ny的步数加一
res[nx][ny] = res[x][y] + 1;
//放在队列中
((LinkedList<point>) q).push(new point(nx, ny));
}
}
}
}
}
}
public static void main(String[] args) {
ZouMIGong_bfs a = new ZouMIGong_bfs();
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
int sx=0;
int sy=0;
char[][] dt = new char[x][y];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
dt[i][j] = sc.next().charAt(0);
if (dt[i][j]=='S'){
sx=i;
sy=j;
}
}
}
a.bfs(sx,sy,dt);
System.out.println(ress);
}
}