Code One:
#include <iostream>#include<cstdio>#include<queue>using namespacestd;Const intmax_n=205;Const intinf=0x30303030;CharMap[max_n][max_n];intn,m;intSx,sy;intGx,gy;intdx[4]={1,0, -1,0};intdy[4]={0,1,0, -1};typedef pair<int,int>P;intDist[max_n][max_n];intBFsintYintx) { for(intI=0; i<n; i++) for(intj=0; j<m; J + +) Dist[i][j]=INF; DIST[SY][SX]=0; Queue<P>que; Que.push (P (SY,SX)); while(!Que.empty ()) {P pos=Que.front (); Que.pop (); inty=Pos.first; intx=Pos.second; if(y==gy&&x==GX) { Break; } for(intI=0; i<4; i++) { intny=y+Dy[i]; intnx=x+Dx[i]; if(0<=ny&&ny<N&&0<=nx&&nx<m&&map[ny][nx]!='#') { intD; if(map[ny][nx]=='x') {D=dist[y][x]+2; } Else{d=dist[y][x]+1; } if(d>=Dist[ny][nx]) { Continue; } Dist[ny][nx]=D; Que.push (P (NY,NX)); } } } returnDIST[GY][GX];}intMain () { while(cin>>n>>M) { for(intI=0; i<n; i++) { for(intj=0; j<m; J + +) {cin>>Map[i][j]; if(map[i][j]=='R') {sy=i; SX=J; } if(map[i][j]=='a') {Gy=i; GX=J; } } } intexist=BFS (SY,SX); if(exist==INF) {cout<<"Poor ANGEL have to stay in the prison all he life."<<Endl; } Else{cout<<exist<<Endl; } } return 0;}
Code two:
#include"iostream"#include"Queue"using namespacestd;Const intinf=0x30303030;Const intmax_n=205;intN, M;CharMap[max_n][max_n];intsy, SX;intGX, Gy;intdx[4]={1,0, -1,0};intdy[4]={0,1,0, -1};intD[max_n][max_n];structnode{inty; intx; intstep; Node (intYintXintStep) { This->y=y; This->x=x; This->step=step; }friendBOOL operator<(node No1, node NO2) {returnNo1.step >No2.step; }};voidDfs () { for(intI=0; i<n; i++) { for(intj=0; j<m; J + +) {D[i][j]=INF; } } intans; BOOLexist=false; Priority_queue<node>que; Que.push (Node (SY,SX,0)); while(!Que.empty ()) {Node now=que.top (); Que.pop (); if(now.y==gy&&now.x==GX) {ans=Now.step; exist=true; Break; } for(intI=0; i<4; i++) { intny=now.y+Dy[i]; intnx=now.x+Dx[i]; if(0<=ny&&ny<N&&0<=nx&&nx<m&&map[ny][nx]!='#') { intDist; if(map[ny][nx]=='x') {Dist=now.step+2; } Else{Dist=now.step+1; } if(Dist>=d[ny][nx])Continue; D[NY][NX]=Dist; Que.push (Node (ny,nx,dist)); } } } if(exist) {cout<<ans<<Endl; } Else{cout<<"Poor ANGEL have to stay in the prison all he life."<<Endl; }}intMain () { while(cin>>n>>M) { for(intI=0; i<n; i++) { for(intj=0; j<m; J + +) {cin>>Map[i][j]; if(map[i][j]=='R') {sy=i; SX=J; } if(map[i][j]=='a') {Gy=i; GX=J; }}} dfs (); } return 0;}
HDOJ1242 (Time-lapse maze BFS)