HDU-1242-Rescue
Http://acm.hdu.edu.cn/showproblem.php? Pid = 1, 1242
Bfs is enough. There may be multiple 'R', and 'A' has only one. From 'A', the first 'r' is the desired one.
It should be noted that there are obstacles in this wide search. If 'X' is encountered, the time is + 2. If a common queue is used, it cannot be ensured that each time the team leaves is the smallest element of time, so we need to use the priority queue. The first time we use the priority queue, we are not very familiar with it.
Basic operations of priority_queue:
Empty (); 1 is returned if the queue is empty
Pop (); team out
Push (); join
Top (); returns the element with the highest priority in the queue.
Size (); returns the number of elements in the queue.
# Include <iostream> # include <cstdio> # include <cstring> # include <cstdlib> # include <queue> using namespace std; char map [205] [205]; int visit [205] [205]; int dir [4] [2] = {-}, {}, {0,-1 }}; int n, m; struct node {int x, y; int time; friend bool operator <(const node & a, const node & B) // leave the team for a short time {return. time> B. time ;}}; int go (int x, int y) {if (0 <= x & x <n & 0 <= y & y <m & map [x] [y]! = '#') Return 1; return 0;} int bfs (int x, int y) {int I; node st, ed; priority_queue <node> que; // define a priority queue for memset (visit, 0, sizeof (visit); st. x = x; st. y = y; st. time = 0; visit [st. x] [st. y] = 1; que. push (st); while (! Que. empty () {st = que. top (); que. pop (); if (map [st. x] [st. y] = 'R') return st. time; for (I = 0; I <4; I ++) {ed. x = st. x + dir [I] [0]; ed. y = st. y + dir [I] [1]; if (go (ed. x, ed. y )&&! Visit [ed. x] [ed. y]) {visit [ed. x] [ed. y] = 1; if (map [ed. x] [ed. y] = 'X') ed. time = st. time + 2; elseed. time = st. time + 1; que. push (ed) ;}}} return-1 ;}int main () {int I, j; int x, y, ans; while (scanf ("% d", & n, & m )! = EOF) {for (I = 0; I <n; I ++) scanf ("% s", map [I]); for (I = 0; I <n; I ++) for (j = 0; j <m; j ++) if (map [I] [j] = 'A ') {x = I; y = j; break;} ans = bfs (x, y); if (ans =-1) printf ("Poor ANGEL has to stay in the prison all his life. \ n "); elseprintf (" % d \ n ", ans);} return 0 ;}