题目
总时间限制: 1000ms 内存限制: 65536kB
描述
公主被恶人抓走,被关押在牢房的某个地方。牢房用N*M (N, M <= 200)的矩阵来表示。矩阵中的每项可以代表道路(@)、墙壁(#)、和守卫(x)。
英勇的骑士(r)决定孤身一人去拯救公主(a)。我们假设拯救成功的表示是“骑士到达了公主所在的位置”。由于在通往公主所在位置的道路中可能遇到守卫,骑士一旦遇到守卫,必须杀死守卫才能继续前进。
现假设骑士可以向上、下、左、右四个方向移动,每移动一个位置需要1个单位时间,杀死一个守卫需要花费额外的1个单位时间。同时假设骑士足够强壮,有能力杀死所有的守卫。
给定牢房矩阵,公主、骑士和守卫在矩阵中的位置,请你计算拯救行动成功需要花费最短时间。
输入
第一行为一个整数S,表示输入的数据的组数(多组输入)
随后有S组数据,每组数据按如下格式输入
1、两个整数代表N和M, (N, M <= 200).
2、随后N行,每行有M个字符。”@”代表道路,”a”代表公主,”r”代表骑士,”x”代表守卫, “#”代表墙壁。
输出
如果拯救行动成功,输出一个整数,表示行动的最短时间。
如果不可能成功,输出”Impossible”
样例输入
样例输出
13
7
思路
BFS。用队列记录走的节点和时间,遇到守卫时,时间+1,方向不变。
代码
while True:
try:
S = int(input())
for _ in range(S):
N, M = input().strip().split()
N = int(N); M = int(M)
grid = []
r, c = 0, 0
for i in range(N):
grid.append(list(input()))
if 'r' in grid[i]:
r, c = i, grid[i].index('r')
visited = [[0 for i in range(M)] for _ in range(N)]
directions = [[-1, 0], [1, 0], [0, 1], [0, -1]]
queue = []
queue.append([r, c, 0])
visited[r][c] = 1
found = False
while len(queue):
tmp = queue[0]
queue.pop(0)
if grid[tmp[0]][tmp[1]] == 'a':
print(tmp[2])
found = True
break
if grid[tmp[0]][tmp[1]] == 'x':
queue.append([tmp[0], tmp[1], tmp[2] + 1])
grid[tmp[0]][tmp[1]] = '@'
else:
for direction in directions:
new_r = tmp[0] + direction[0]
new_c = tmp[1] + direction[1]
if new_r >= 0 and new_r < N and new_c >= 0 and new_c < M and visited[new_r][new_c] == 0 and grid[new_r][new_c] != '#':
queue.append([new_r, new_c, tmp[2] + 1])
visited[new_r][new_c] = 1
if not found:
print('Impossible')
except:
break