Saving Princess claire_&&http://acm.hdu.edu.cn/showproblem.php?pid=4308

来源:互联网 发布:黑茶网络营销策划 编辑:程序博客网 时间:2024/06/14 14:41

BFS入门题。。

AC代码:

#include<iostream>#include<cstdio>#include<string.h>#include<string>#include<queue>#include<set> Q;#define N 5005using namespace std;typedef struct node{int x;int y;int step;bool flag;bool operator<(const node& a){return a.step<step;}}Node;char map[N][N];Node now,last,cur;int endx,endy;int n,m,cost;int dx[]={0,0,1,-1};int dy[]={1,-1,0,0};queue<Node>Q;int bfs(){queue<Node>Q1;now.step=0;now.flag=0;Q1.push(now);map[now.x][now.y]='#';while(!Q1.empty()){cur=Q1.front();Q1.pop();int sa=cur.x;int sb=cur.y;int step=cur.step;int flag=cur.flag;if(flag){while(!Q.empty()){now=Q.front(); Q.pop();  int a=now.x;  int b=now.y;  if(map[a][b]!='#') {  now.x=a,now.y=b,now.step=step,now.flag=1,Q1.push(now);      map[a][b]='#';    }}}for(int i=0;i!=4;++i){int xx=sa+dx[i];int yy=sb+dy[i];if(xx==endx&&yy==endy) return step;if(xx>=0&&xx<n&&yy>=0&&yy<m&&map[xx][yy]!='#'){now.x=xx,now.y=yy;if(map[xx][yy]=='*') {now.step=step+cost,now.flag=0;}else if(map[xx][yy]=='P'){now.step=step;now.flag=1;}Q1.push(now),map[xx][yy]='#';}}}return -1;}int main(){ while(cin>>n>>m>>cost)   {            memset(map,'0',sizeof(map));        for(int i=0;i<n;i++)        {  cin>>map[i];          for(int j=0;j<m;j++)           {                  if(map[i][j]=='Y'){now.x=i;now.y=j;}  else if(map[i][j]=='C') {endx=i;endy=j;}   else if(map[i][j]=='P') {last.x=i,last.y=j;Q.push(last);}           }         }int ans=bfs();if(ans==-1) cout<<"Damn teoy!"<<endl;else cout<<ans<<endl;            }return 0;}