POJ 2312 Battle City (priority queue + BFS)

Source: Internet
Author: User

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;
 }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.