优先队列BFS
一、描述
优先队列适用于一张边权为任意不同数的图,即优化的 D i j k s t r a Dijkstra Dijkstra 算法;
由于优先队列会让元素优先级最大的先出队,所以可利用此特性进行搜索;
若用普通的搜索由于边权不同,搜索可能难以得到最优解;
求最值时,使用优先对列对每种扩展的状态进行排序,每次取出队首时,一定的到优先级最大的,即可找到最优解;
此方法可以保证出队元素的单调性;
二、例题
Battle City
题目
Your tank can’t move through rivers or walls, but it can destroy brick walls by shooting. A brick wall will be turned into empty spaces when you hit it, however, if your shot hit a steel wall, there will be no damage to the wall. In each of your turns, you can choose to move to a neighboring (4 directions, not 8) empty space, or shoot in one of the four directions without a move. The shot will go ahead in that direction, until it go out of the map or hit a wall. If the shot hits a brick wall, the wall will disappear (i.e., in this turn). Well, given the description of a map, the positions of your tank and the target, how many turns will you take at least to arrive there?
题目大意:
起点为Y,遇到R和S不能走,遇到B花费为2,遇到E花费为1,问走到T的花费最小是多少。
输入格式
The input consists of several test cases. The first line of each test case contains two integers M and N (2 <= M, N <= 300). Each of the following M lines contains N uppercase letters, each of which is one of ‘Y’ (you), ‘T’ (target), ‘S’ (steel wall), ‘B’ (brick wall), ‘R’ (river) and ‘E’ (empty space). Both ‘Y’ and ‘T’ appear only once. A test case of M = N = 0 indicates the end of input, and should not be processed.
输出格式
For each test case, please output the turns you take at least in a separate line. If you can’t arrive at the target, output “-1” instead.
思路
因为每个点的花费不一样,那么用优先队列加广搜,优先走步数最小的;
搜索时扩展四个方向,将四个状态放入优先队列中,再从对首继续扩展即可;
代码
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#define MAXN 3005
using namespace std;
int n, m, sx, sy, ex, ey;
char c[MAXN][MAXN];
bool flag[MAXN][MAXN];
int wayx[5] = { 0, 0, 1, -1 };
int wayy[5] = { 1, -1, 0, 0 };
struct point {
int x, y, z;
bool operator < (const point a) const {
return z > a.z;
}
} t;
int bfs (int sx, int sy, int ex, int ey) {
priority_queue < point > q;
q.push( point ( { sx, sy, 0 } ) );
flag[sx][sy] = true;
while (!q.empty()) {
t = q.top();
q.pop();
int xr = t.x, yr = t.y, zr = t.z;
if (xr == ex && yr == ey) {
return t.z;
}
for (int i = 0; i < 4; i++) {
int dx = xr + wayx[i], dy = yr + wayy[i], dz = zr;
if (dx > 0 && dx <= m && dy > 0 && dy <= n && c[dx][dy] != 'R' && c[dx][dy] != 'S' && flag[dx][dy] == false) {
flag[dx][dy] = true;
if (c[dx][dy] == 'B') {
dz++;
}
dz++;
q.push( point ( { dx, dy, dz } ) );
}
}
}
return -1;
}
int main() {
while (1) {
scanf("%d %d", &m, &n);
if (n == 0 && m == 0) return 0;
memset(flag, false, sizeof(flag));
for (int i = 1; i <= m; i++) {
scanf("\n");
for (int j = 1; j <= n; j++) {
scanf("%c", &c[i][j]);
if (c[i][j] == 'Y') {
sx = i, sy = j;
} else if (c[i][j] == 'T') {
ex = i, ey = j;
}
}
}
printf("%d\n", bfs(sx, sy, ex, ey));
}
return 0;
}