poj2312优先队列BFS

题目链接:点击打开链接

题意:

给你一个m行n列的矩阵。

Y代表起点,T代表终点。B、E可以走,S、R不可以走,B的时间花费为2,E为1.

求Y到T的最短时间。

思路:用优先队列BFS一遍就可以了

#include <iostream>
#include<cstdio>
#include<cstring>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cstdlib>
using namespace std;
const int maxn=500+10;
const int xx[]={0,0,1,-1};
const int yy[]={1,-1,0,0};
int m[maxn][maxn],vis1[maxn][maxn],vis2[maxn][maxn][4];
int N,M,c1,c2,r1,r2;
 struct node
{
    int x,y,dis,dir;//dir表示方向
       friend bool operator <(node a,node b)
    {
       return a.dis>b.dis;
    }
};
int check(int x,int y)
{
   if(x>0&&x<=N&&y>0&&y<=M&&m[x][y]!=-1)return 1;
   return 0;
}
int bfs1()
{
    if(c1 == c2&& r1 == r2)
        return 0;
    priority_queue<node> q;
    memset(vis1,0,sizeof(vis1));
    node temp,next;
    temp.x = r1 ;
    temp.y = c1 ;
    temp.dis = m[r1][c1];
    q.push(temp);
    vis1[r1][c1] = 1;
    while(!q.empty())
    {
        temp = q.top();
        q.pop();
        if(temp.x == r2&&temp.y == c2)
            return temp.dis;
        for(int i = 0 ; i < 4; i ++)
        {
            int nx = temp.x + xx[i];
            int ny = temp.y + yy[i];
            next.x=nx,next.y=ny;
            if(check(nx,ny)&&!vis1[nx][ny])
            {
                vis1[nx][ny] = 1;
               next.dis = temp.dis +m[nx][ny];
                q.push(next);
            }

        }
    }
    return -1;
}
int main()
{

 int ans=0,i,j;
 char s[300+10];
 while(~scanf("%d %d",&N,&M)&&(N+M))
 {
    memset(m,0x3f,sizeof(m));
    for(i=1;i<=N;i++)
    {
        scanf("%s",s+1);
       // printf("%s\n",s+1);
     for(j=1;j<=M;j++)
     {
          if(s[j]=='S'||s[j]=='R')m[i][j]=-1;
      else if(s[j]=='Y')
      {
          m[i][j]=0;
          r1=i,c1=j;
      }
      else if(s[j]=='T')
      {
          m[i][j]=1;
          r2=i,c2=j;
      }
      else if(s[j]=='B')m[i][j]=2;
      else if(s[j]=='E')m[i][j]=1;
     }
    }
     printf("%d\n",bfs1());
 }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值