ʕ·͡ˑ·ཻ ʕ•̫͡• ʔ•̫͡•ཻʕ•̫͡•ʔ•͓͡•ʔ

题目–拯救行动

描述

公主被恶人抓走,被关押在牢房的某个地方。牢房用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”

样例输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
7 8
#@#####@
#@a#@@r@
#@@#x@@@
@@#@@#@#
#@@@##@@
@#@@@@@@
@@@@@@@@
13 40
@x@@##x@#x@x#xxxx##@#x@x@@#x#@#x#@@x@#@x
xx###x@x#@@##xx@@@#@x@@#x@xxx@@#x@#x@@x@
#@x#@x#x#@@##@@x#@xx#xxx@@x##@@@#@x@@x@x
@##x@@@x#xx#@@#xxxx#@@x@x@#@x@@@x@#@#x@#
@#xxxxx##@@x##x@xxx@@#x@x####@@@x#x##@#@
#xxx#@#x##xxxx@@#xx@@@x@xxx#@#xxx@x#####
#x@xxxx#@x@@@@##@x#xx#xxx@#xx#@#####x#@x
xx##@#@x##x##x#@x#@a#xx@##@#@##xx@#@@x@x
x#x#@x@#x#@##@xrx@x#xxxx@##x##xx#@#x@xx@
#x@@#@###x##x@x#@@#@@x@x@@xx@@@@##@@x@@x
x#xx@x###@xxx#@#x#@@###@#@##@x#@x@#@@#@@
#@#x@x#x#x###@x@@xxx####x@x##@x####xx#@x
#x#@x#x######@@#x@#xxxx#xx@@@#xx#x#####@

样例输出

1
2
13
7

题意:

​ 之前是用单纯的BFS,遇到x时step+2,遇到@时step+1,这样做不行然后我看了别人的博客,因为这样做求得的只是最短路的时间而不是最短时间,说明我对BFS理解还不是很深刻,所以这就不是一道常规的BFS题目了,有两种解题方式,一种是把x的两秒当成走两步,另一种是用BFS+优先队列。

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<bits/stdc++.h>
using namespace std;
char maze[205][205];
int vis[205][205];
int dir[4][2] = {-1, 0, 0, -1, 1, 0, 0, 1};
struct node {
int x, y, step;
bool operator < (const node &a) const {
return step > a.step;
}
};
int n, m;
int flag;
node st, ne;
int BFS() {
priority_queue < node > q;
q.push(st);
while(!q.empty()) {
st = q.top();
q.pop();
for(int i = 0; i < 4; i++) {
ne.x = st.x + dir[i][0];
ne.y = st.y + dir[i][1];
if(ne.x >= 1 && ne.x <= n && ne.y >= 1 && ne.y <=m && !vis[ne.x][ne.y]) {
if(maze[ne.x][ne.y] == '@') {
ne.step = st.step + 1;
q.push(ne);
vis[ne.x][ne.y] = 1;
}
else if(maze[ne.x][ne.y] == 'x') {
ne.step = st.step + 2;
q.push(ne);
vis[ne.x][ne.y] = 1;
}
else if(maze[ne.x][ne.y] == 'a') {
flag = 1;
return st.step + 1;
}
else if(maze[ne.x][ne.y] == '#') {
vis[ne.x][ne.y] = 1;
}
}
}
}
}
int main() {
int s;
cin>>s;
while(s--) {
memset(vis, 0, sizeof(vis));
flag = 0;
cin>>n>>m;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
cin>>maze[i][j];
if(maze[i][j] == 'r') {
st.x = i;
st.y = j;
st.step = 0;
vis[st.x][st.y] = 1;
}
}
}
int ans = BFS();
if(flag) cout<<ans<<endl;
else cout<<"Impossible"<<endl;
}
return 0;
}