POJ 2312(BFS+优先队列)

20 篇文章 0 订阅
11 篇文章 0 订阅
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值