当各个节点的权重一样的时候,最小代价的路径=最短距离路径。可以把bfs理解为每次扩张一圈,只要记录每个节点在第几圈即可,与具体怎么从一个圈到达另一个圈的路径无关。
解法一:bfs+优先队列
当每个节点权重不一样时,要想使每个节点的代价最小,只要保证所有能到达它的节点的代价都是最小的,并从中选择最小的那个用来确定它的代价即可。
bfs+优先队列中,每次出队的时候,出队元素的代价都是全局最小的,因为之后入队节点的代价一定大于当前队列中所有节点的代价,而每次出队的又都是当前队列中代价最小的元素。节点出队时,会更新所有与它相邻节点的代价,全局最小代价一定满足上述的条件。所以每个节点的代价都是最小的。
//优先队列
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 205;
char mp[MAXN][MAXN];
int n, m, spt[MAXN][MAXN];
int dir[][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
struct node {
int x, y, t;
node(int x_, int y_, int t_) : x(x_), y(y_), t(t_) {}
friend bool operator <(node a,node b){
return a.t>b.t;//右边的是优先级更高的,比如这里就是t越小优先级越高
}
};
int BFS(int x, int y, int x_, int y_) {
mp[x][y] = '#';//标记起始点
priority_queue <node> Q;
Q.push(node(x, y, 0));
while (!Q.empty()) {
node p = Q.top();
Q.pop();
if (p.x == x_ && p.y == y_)
return p.t;
for (int i = 0; i < 4; i++) {
int tx = p.x + dir[i][0];
int ty = p.y + dir[i][1];
if (tx >= 0 && tx < n && ty >= 0 && ty < m && mp[tx][ty] != '#') {
int t = p.t + 1;
if (mp[tx][ty] == 'x')
t++;
mp[tx][ty] = '#';
Q.push(node(tx, ty, t));
}
}
}
return -1;
}
int main() {
int t, ex, ey, sx, sy;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf(" %c", &mp[i][j]);
if (mp[i][j] == 'r')
sx = i, sy = j;
else if (mp[i][j] == 'a')
ex = i, ey = j;
}
}
int ans = BFS(sx, sy, ex, ey);
if (~ans)
printf("%d\n", ans);
else printf("Impossible\n");
}
return 0;
}