POJ 2312(BFS+优先队列)

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
const int MAX = 350;
int m, n, sx, sy, ex, ey, ans, map[MAX][MAX], vis[MAX][MAX];
int dir[8] = {1, 0, -1, 0, 0, 1, 0, -1};
struct node
{
    int x, y, z;
    node(int x, int y, int z):x(x),y(y),z(z) {}
    friend bool operator < (node a, node b)
    {
        return a.z > b.z; //结构体中,z小的优先级高
    }
};
int BFS(int x, int y, int z)
{
    priority_queue<node>v;
    v.push(node(x, y, z));
    vis[x][y] = 1;
    while (!v.empty())
    {
        node cur = v.top();
        v.pop();
        if (cur.x == ex && cur.y == ey)
            return cur.z;
        for (int i = 0; i < 8; )
        {
            int n_x = cur.x + dir[i++];
            int n_y = cur.y + dir[i++];
            if (n_x >= 1 && n_x <= m && n_y >= 1 && n_y <= n && !vis[n_x][n_y] && map[n_x][n_y])
            {   
                vis[n_x][n_y] = 1;
                int n_z = cur.z + map[n_x][n_y];
                v.push(node(n_x, n_y, n_z));
            }
        }
    }
    return -1;
}
int main()
{
    while (scanf("%d%d", &m, &n), m + n)
    {
        getchar();
        for (int i = 0; i < MAX; i++)
        {
            for (int j = 0; j < MAX; j++)
            {
                map[i][j] = vis[i][j] = 0;
            }
        }
        for (int i = 1; i <= m; i++)
        {
            for (int j = 1; j <= n; j++)
            {
                char ch = getchar();
                switch (ch)
                {
                    case 'Y': sx = i, sy = j, map[i][j] = 1; break;                    
                    case 'E': map[i][j] = 1; break;                    
                    case 'B': map[i][j] = 2; break;                    
                    case 'R': map[i][j] = 0; break;                    
                    case 'S': map[i][j] = 0; break;                    
                    case 'T': ex = i, ey = j, map[i][j] = 1; break;                    
                }
            }
            getchar();
        }
        ans = 0;
        printf("%d\n", BFS(sx, sy, 0));
    }
    return 0;
}

你可能感兴趣的:(搜索,poj,优先队列)