文章标题 CSU 1815 : Enterprising Escape(BFS--优先队列)

来源:互联网 发布:淘宝直播端口 编辑:程序博客网 时间:2024/05/01 05:03

Enterprising Escape

1815: Enterprising Escape
题意:在一个w*h的矩形中,存在这每个单元有一个字符表示,总共有k中字符,每个字符有一个键值,表示要走过这个字符需要花费的时间,然后在这个矩阵中还有一个字符“E”,表示你所在的位置,然后要求从当前这个位置(即E的位置)走出这个矩阵花费的最少的时间。
分析:首先,每个字符和相应的键值可以用一个map来维护,然后可以看出来直接用BFS求解,然后由于要求最少时间,所以得用到优先队列,所需时间越短,优先级越高。每次出队判断当前点的位置是否在边界,是的话就直接返回时间。
代码:

#include<iostream>#include<string>#include<cstdio>#include<cstring>#include<vector>#include<math.h>#include<map>#include<queue> #include<algorithm>using namespace std;const double pi=acos(-1.0);const int inf = 0x3f3f3f3f;const int maxn=100005;const double eps=1e-8; map<char,int>mp;char G[1005][1005]; int k,w,h;int dx[4]={1,0,-1,0};//四个方向 int dy[4]={0,1,0,-1};struct node {    int x,y,cost;    bool operator <(const node &t)const{//优先级         return cost>t.cost;    }};bool check(int x,int y){//判断是否在边界     return x==0||x==h-1||y==0||y==w-1; }int vis[1005][1005];//标记点是否已被访问 int bfs(int x,int y){    memset (vis,0,sizeof (vis));//初始化     vis[x][y]=1;    priority_queue<node> q;    q.push((node){x,y,0});    while (!q.empty()){        node tmp=q.top();q.pop();        int nx=tmp.x;        int ny=tmp.y;        if (check(nx,ny)) return tmp.cost;//如果到边界直接返回         for (int i=0;i<4;i++){            nx=tmp.x+dx[i];ny=tmp.y+dy[i];//遍历四个方向             if (vis[nx][ny])continue;//如果已经访问过了就直接跳过             vis[nx][ny]=1;            q.push((node{nx,ny,tmp.cost+mp[G[nx][ny]]}));//否则放进队列         }    } }int main(){    int t;    scanf ("%d",&t);    while (t--){        scanf ("%d%d%d",&k,&w,&h);        mp.clear();//map         char c[5];        int val;        for (int i=0;i<k;i++){            scanf ("%s%d",c,&val);            mp[c[0]]=val;//一个字符映射成相应的键值         }        int x,y;        for (int i=0;i<h;i++){            scanf ("%s",G[i]);            for (int j=0;j<w;j++){                if (G[i][j]=='E'){                    x=i,y=j;//标记初始点                 }            }        }        int ans=bfs(x,y);        printf ("%d\n",ans);    }    return 0; } 
0 0