标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1026
5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX. 5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX1 5 6 .XX... ..XX1. 2...X. ...XX. XXXXX.
It takes 13 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) FINISH It takes 14 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) 14s:FIGHT AT (4,5) FINISH God please help our poor hero. FINISH
代码:
#include<iostream> #include<queue> #include<cstring> #include<cstdio> using namespace std; int n,m; char Map[150][150]; int vis[150][150]; int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; typedef struct NODE { int x,y; }NODE; struct node { int s; NODE now; NODE pre; friend bool operator <(node a,node b) { return a.s>b.s; } }a[150][150]; void init() { memset(vis,0,sizeof(vis)); } bool check(int x,int y) { return !vis[x][y]&&x>=0&&y>=0&&x<n&&y<m&&(Map[x][y]!='X'); } void print(node st) { cout<<"It takes "<<st.s<<" seconds to reach the target position, let me show you the way."<<endl; NODE route[10050]; route[0]=st.now; int cnt=1; while(st.now.x!=0||st.now.y!=0){ st=a[st.pre.x][st.pre.y]; route[cnt++]=st.now; } int t=1; for(int i=cnt-1;i>0;i--){ if(Map[route[i].x][route[i].y]!='.'){ char tt=Map[route[i].x][route[i].y]; while(tt!='0'){ cout<<t++<<"s:FIGHT AT ("<<route[i].x<<','<<route[i].y<<")"<<endl; tt--; } } cout<<t++<<"s:("<<route[i].x<<','<<route[i].y<<")->("<<route[i-1].x<<','<<route[i-1].y<<')'<<endl; } if(Map[route[0].x][route[0].y]!='.'){ char tt=Map[route[0].x][route[0].y]; while(tt!='0'){ cout<<t++<<"s:FIGHT AT ("<<route[0].x<<','<<route[0].y<<")"<<endl; tt--; } } return; } void bfs() { priority_queue<node>q; node st; st.s=0; st.now.x=0; st.now.y=0; st.pre.x=0; st.pre.y=0; a[0][0]=st; vis[0][0]=1; q.push(st); while(!q.empty()){ st=q.top(); q.pop(); if(st.now.x==n-1&&st.now.y==m-1){ print(st); //cout<<st.s<<endl; return; } for(int i=0;i<4;i++){ node nt=st; nt.pre.x=st.now.x; nt.pre.y=st.now.y; nt.now.x+=dir[i][0]; nt.now.y+=dir[i][1]; if(check(nt.now.x,nt.now.y)){ vis[nt.now.x][nt.now.y]=1; a[nt.now.x][nt.now.y]=nt; int t=1; if(Map[nt.now.x][nt.now.y]!='.'){ t+=Map[nt.now.x][nt.now.y]-'0'; } nt.s+=t; q.push(nt); } } } cout<<"God please help our poor hero."<<endl; } int main() { cin.sync_with_stdio(false); while(cin>>n>>m){ init(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cin>>Map[i][j]; } } bfs(); cout<<"FINISH"<<endl; } return 0; }
【BFS】HDU1026Ignatius and the Princess I
标签:
原文地址:http://blog.csdn.net/wlxsq/article/details/51353324