标准的bfs,不过和花束一点关系都没有…
bfs模板,再复习一遍
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.PriorityQueue;
import java.util.Queue;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 210, T, n, m;
static int dist[][] = new int[N][N];
static char g[][] = new char[N][N];
static int dx[] = new int[]{0, 1, 0, -1};
static int dy[] = new int[]{1, 0, -1, 0};
public static void main(String[] args) throws IOException {
T = Integer.parseInt(br.readLine());
String s[];
while (T-- > 0) {
s = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
for (int i = 0; i < n; i++) {
String ss = br.readLine();
for (int j = 0; j < m; j++) {
g[i][j] = ss.charAt(j);
}
}
Pair start = new Pair(-1, -1), end = new Pair(-1, -1);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == 'E') end = new Pair(i, j);
else if (g[i][j] == 'S') start = new Pair(i, j);
}
}
int res = bfs(start, end);
if (res != -1) pw.println(res);
else pw.println("oop!");
}
pw.flush();
pw.close();
br.close();
}
public static int bfs(Pair start, Pair end) {
Queue<Pair> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
dist[i][j] = -1;
}
dist[start.x][start.y] = 0;
q.offer(start);
while (!q.isEmpty()) {
Pair temp = q.poll();
for (int i = 0; i < 4; i++) {
int x = temp.x + dx[i];
int y = temp.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= m) continue;
if (g[x][y] == '#') continue;
if (dist[x][y] != -1) continue;
dist[x][y] = dist[temp.x][temp.y] + 1;
if (x == end.x && y == end.y) return dist[x][y];
q.offer(new Pair(x, y));
}
}
return -1;
}
}
class Pair {
public int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}