python代码
from collections import deque
# 读取测试用例数量
T = int(input())
# 方向数组 (上下左右)
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
# 获取相邻点的有效位置
def getNeighbors(cur, n, m):
x, y = cur
res = []
for dx, dy in directions:
new_x = x + dx
new_y = y + dy
if 0 <= new_x < n and 0 <= new_y < m:
res.append((new_x, new_y))
return res
# BFS 搜索最短路径
def bfs(L, start_x, start_y, end_x, end_y, n, m):
q = deque([(start_x, start_y)])
visit = set()
visit.add((start_x, start_y))
step = 0
while q:
sz = len(q)
for _ in range(sz):
cur = q.popleft()
# 如果到达终点
if cur == (end_x, end_y):
return step
# 扩展相邻点
for to in getNeighbors(cur, n, m):
if to not in visit and L[to[0]][to[1]] in {".", "E"}:
q.append(to)
visit.add(to)
step += 1
return -1 # 无法到达终点
# 多组测试数据
for _ in range(T):
n, m = map(int, input().split())
L = []
start_x = start_y = end_x = end_y = 0
for i in range(n):
s = input().strip()
row = list(s)
for j in range(m):
if row[j] == "S":
start_x, start_y = i, j
if row[j] == "E":
end_x, end_y = i, j
L.append(row)
# 起点和终点相同
if (start_x, start_y) == (end_x, end_y):
print(0)
continue
# 执行 BFS
result = bfs(L, start_x, start_y, end_x, end_y, n, m)
if result == -1:
print("oop!")
else:
print(result)