AcWing 1101. 献给阿尔吉侬的花束
原题链接
简单
作者:
不知名的fE
,
2024-11-24 15:56:27
,
所有人可见
,
阅读 1
import java.util.*;
public class Main {
static final int N = 210;
static char[][] g = new char[N][N];
static int[][] d = new int[N][N];
static boolean[][] st = new boolean[N][N];
static int[] dx = {1, -1, 0, 0}, dy = {0, 0, -1, 1};
static int T, r, c;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
T = Integer.parseInt(sc.nextLine());
while (T-- > 0) {
String[] s = sc.nextLine().split(" ");
r = Integer.parseInt(s[0]);
c = Integer.parseInt(s[1]);
for (int i = 0; i < r; i++) Arrays.fill(st[i], 0, c, false);//初始化
int x = -1, y = -1;
for (int i = 0; i < r; i++) {
g[i] = sc.nextLine().toCharArray();
for (int j = 0; j < c; j++) {
if (g[i][j] == 'S') {
x = i;
y = j;
}
}
}
int ans = bfs(x, y);
System.out.println(ans == -1 ? "oop!" : ans);
}
}
static int bfs(int a, int b) {
int ans = -1;
LinkedList<int[]> queue = new LinkedList<>();
d[a][b] = 0;
st[a][b] = true;
queue.offer(new int[]{a, b});
while (!queue.isEmpty()) {
boolean flag = false;
int[] t = queue.poll();
for (int i = 0; i < 4; i++) {
int x = dx[i] + t[0], y = dy[i] + t[1];
if (x >= 0 && x < r && y >= 0 && y < c && !st[x][y] && g[x][y] != '#') {
st[x][y] = true;
d[x][y] = d[t[0]][t[1]] + 1;
queue.offer(new int[]{x, y});
if (g[x][y] == 'E') {
ans = d[x][y];
flag = true;
break;
}
}
}
if (flag) break;
}
return ans;
}
}