迷宫最短路问题,用bfs会更快一点。
输入:
5 6
....S*
.**...
.*..*.
*..**.
.T....
输出:
7
代码如下:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class L2 {
static int n, m, ans = 0;
static char[][] map = new char[110][110];
static boolean[][] vis = new boolean[110][110];
static int[][] dir = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } };
static boolean in(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m;
}
static int bfs(int sx, int sy) {
Queue<Node> q = new LinkedList<>();
q.offer(new Node(sx, sy, 0));
vis[sx][sy] = true;
while (!q.isEmpty()) {
Node now = q.poll();
for (int i = 0; i < 4; i++) {
int tx = now.x + dir[i][0];
int ty = now.y + dir[i][1];
if (in(tx, ty) && !vis[tx][ty] && map[tx][ty] != '*') {
if (map[tx][ty] == 'T') {
return now.d + 1;
} else {
vis[tx][ty] = true;
q.offer(new Node(tx, ty, now.d + 1));
}
}
}
}
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
for(int i=0;i<n;i++) {
map[i]=sc.next().toCharArray();
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(map[i][j]=='S') {
ans=bfs(i,j);
}
}
}
System.out.println(ans);
}
}
class Node {
int x, y, d;
public Node(int x, int y, int d) {
this.x = x;
this.y = y;
this.d = d;
}
}