Title Link: POJ 2312 Battle City
It takes two steps to break a brick, if it is directly added to the normal queue can be said to violate the rules of BFS, so you need to use the priority queue to select the current queue of the least number of steps, drawing is clear.
Remember to empty the queue.
#include <iostream> #include <cstring> #include <cstdio> #include <queue> using namespace std;
const int MAX_N = 300 + 10;
const int INF = (1 << 29);
struct point {int x, y, dis;
friend bool Operator < (point A, point B) {return a.dis > B.dis;
} point (int x, int y, int dis): x (x), Y (y), dis (dis) {};
Point () {};
};
Priority_queue <Point> Q;
int Vis[max_n][max_n];
Char _map[max_n][max_n];
int fx[4] = {0, 1, 0,-1};
int fy[4] = {1, 0,-1, 0};
int N, M, res;
void BFS () {int dx, dy;
Point A; while (!
Q.empty ()) {a = Q.top ();
if (_map[a.x][a.y] = = ' T ') {res = A.dis;
return;
} q.pop ();
for (int i = 0; i < 4; i++) {dx = a.x + fx[i], dy = a.y + fy[i]; if (dx >= 0 && dy >= 0 && dx < N && dy < M &&!vis[dx][dy] && _map[dx][ DY]! = ' S ' &&
_map[dx][dy]! = ' R ') {vis[dx][dy] = 1;
if (_map[dx][dy] = = ' B ') q.push (point (dx, dy, A.dis + 2));
Else Q.push (point (dx, dy, A.dis + 1)); }}}} int main () {while (scanf ("%d%d", &n, &m), N + M) {memset (Vis, 0, sizeof (VIS)
);
res = INF;
for (int i = 0; i < N; i++) {scanf ("%s", _map[i]); for (int j = 0; J < M; J + +) {if (_map[i][j] = = ' Y ') {VI
S[I][J] = 1;
Q.push (Point (I, J, 0));
}}} BFS ();
if (res = = INF) printf (" -1\n");
else printf ("%d\n", res); while (!
Q.empty ()) Q.pop ();
} return 0;
}