传送门
公主被恶人抓走,被关押在牢房的某个地方。牢房用N*M (N, M <= 200)的矩阵来表示。矩阵中的每项可以代表道路(@)、墙壁(#)、和守卫(x)。
英勇的骑士(r)决定孤身一人去拯救公主(a)。我们假设拯救成功的表示是“骑士到达了公主所在的位置”。由于在通往公主所在位置的道路中可能遇到守卫,骑士一旦遇到守卫,必须杀死守卫才能继续前进。
现假设骑士可以向上、下、左、右四个方向移动,每移动一个位置需要1个单位时间,杀死一个守卫需要花费额外的1个单位时间。同时假设骑士足够强壮,有能力杀死所有的守卫。
给定牢房矩阵,公主、骑士和守卫在矩阵中的位置,请你计算拯救行动成功需要花费最短时间。
Input
第一行为一个整数S,表示输入的数据的组数(多组输入)
随后有S组数据,每组数据按如下格式输入
1、两个整数代表N和M, (N, M <= 200).
2、随后N行,每行有M个字符。"@"代表道路,"a"代表公主,"r"代表骑士,"x"代表守卫, "#"代表墙壁。
Output
如果拯救行动成功,输出一个整数,表示行动的最短时间。
如果不可能成功,输出"Impossible"
Sample Input
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#####@
Sample Output
13
7
思路:
普通广搜不一定是最短路径,有些路径走过去是最小的,但有了有了敌人后就不一定了
eg:
99
2 6
@@@@@@
rxxxxa
这道题需要:优先队列+广搜
每次出来的一定是最短的步数的
代码:
#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll long long
#define PI acos(-1)
#define mes(x,y) memset(x,y,sizeof(x))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
const ll INF = 1e9 + 10;
ll n, m, k, i, j;
string s;
struct node {
ll x, y, z;
node(ll xx,ll yy,ll zz):x(xx),y(yy),z(zz){}
friend bool operator<(node n1, node n2){
return n1.z > n2.z;
}
};
ll mm[300][300];
int main() {
FAST_IO;
while (cin >> k) {
while (k--) {
string a[300];
mes(mm, 0);
priority_queue<node>que;
cin >> n >> m;
ll rx, ry;
for (i = 0; i < n; i++) {
cin >> a[i];
for (j = 0; j < m; j++) {
if (a[i][j] == 'r') {
que.push(node(i, j, 0));
mm[i][j] = 1;
}
if (a[i][j] == 'a') {
rx = i;
ry = j;
}
}
}
ll step[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
ll x, y, z;
while (!que.empty()) {
node nn = que.top(); que.pop();
for (i = 0; i < 4; i++) {
x = nn.x + step[i][0];
y = nn.y + step[i][1];
z = nn.z + 1;
if (x<0 || y<0 || x>=n || y>=m || a[x][y] == '#' || mm[x][y] == 1)continue;
mm[x][y] = 1;
if (a[x][y] == 'a') {
cout << z << endl;
break;
}
if (a[x][y] == 'x')z++;
que.push(node(x, y, z));
}
if (mm[rx][ry])break;
}
if (mm[rx][ry] == 0) {
cout << "Impossible" << endl;
}
}
}
}