nyoj 635 Oh, my goddess 优先队列+BFS

来源:互联网 发布:淘宝店铺装修首页全屏 编辑:程序博客网 时间:2024/06/04 18:36

Shining Knight is the embodiment of justice and he has a very sharp sword can even cleavewall. Many bad guys are dead on his sword.

One day, two evil sorcerer cgangee and Jackchess decided to give him some colorto see. So they kidnapped Shining Knight's beloved girl--Miss Ice! They built a M x Nmaze with magic and shut her up in it.

Shining Knight arrives at the maze entrance immediately. He can reach any adjacent emptysquare of four directions -- up, down, left, and right in 1 second. Or cleave one adjacent wall in 3

seconds, namely,turn it into empty square. It's the time to save his goddess! Notice: ShiningKnight won't leave the maze before he find Miss Ice.

输入
The input consists of blocks of lines. There is a blank line between two blocks.

The first line of each block contains two positive integers M <= 50 and N <= 50separated by one space. In each of the next M lines there is a string of length N contentsO and #.

O represents empty squares. # means a wall.

At last, the location of Miss Ice, ( x, y ). 1 <= x <= M, 1 <= y <= N.

(Shining Knight always starts at coordinate ( 1, 1 ). Both Shining and Ice's locationguarantee not to be a wall.)
输出
The least amount of time Shining Knight takes to save hisgoddess in one line.
样例输入
3 5O##########O#O#3 4
样例输出

14

题意:给你一个地图,O是空白#是墙#,墙需要三分钟变成空白,相当于走一个墙需要4分钟,问你从1,1这个点,走到给你的那个点,最少时间。

优先队列+BFS

#include<iostream>#include<cstdio>#include<cstring>#include<functional>#include<queue>using namespace std;int n,m;char Map[105][105];int book[105][105];int ex,ey;struct node{    int x,y;    int stemp;    friend bool operator <(node n1,node n2){//优先队列        return n1.stemp > n2.stemp;    }}u,e;int text(node a){    if(a.x<=0 || a.x>n || a.y<=0 || a.y>m)        return 0;    return 1;}void BFS(){    int next[4][2]={ {0,1},{1,0},{0,-1},{-1,0} };    int k,i;    priority_queue<node>q;    while(!q.empty()) q.pop();    u.x=1;    u.y=1;    u.stemp=0;    book[u.x][u.y]=1;    q.push(u);    while(!q.empty()){        u=q.top();        q.pop();       // printf("C %d %d %d\n",u.x,u.y,u.stemp);        if(u.x==ex && u.y==ey){            printf("%d\n",u.stemp);            break;        }        for(k=0;k<4;k++){            e.x=u.x+next[k][0];            e.y=u.y+next[k][1];            if(text(e)==1 && book[e.x][e.y]==0){                if(Map[e.x][e.y]=='#')                e.stemp=u.stemp+4;                else                    e.stemp=u.stemp+1;                q.push(e);                //printf("R %d %d %d\n",e.x,e.y,e.stemp);                book[e.x][e.y]=1;            }        }    }}int main(){   int t,i,j;       while(scanf("%d%d",&n,&m)!=EOF){        getchar();       for(i=1;i<=n;i++){           for(j=1;j<=m;j++){             scanf("%c",&Map[i][j]);              book[i][j]=0;           }           getchar();       }       scanf("%d%d",&ex,&ey);       BFS();       }       return 0;}


原创粉丝点击