HDOJ1242(延时迷宫BFS)
2015-08-28 20:05
281 查看
代码一:
代码二:
#include<iostream> #include<cstdio> #include<queue> using namespace std; const int MAX_N=205; const int INF=0x30303030; char map[MAX_N][MAX_N]; int N,M; int sx,sy; int gx,gy; int dx[4]={1, 0, -1, 0}; int dy[4]={0, 1, 0, -1}; typedef pair<int, int> P; int dist[MAX_N][MAX_N]; int bfs(int y, int x) { for(int i=0; i<N; i++) for(int j=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(); int y=pos.first; int x=pos.second; if(y==gy&&x==gx) { break; } for(int i=0; i<4; i++) { int ny=y+dy[i]; int nx=x+dx[i]; if(0<=ny&&ny<N&&0<=nx&&nx<M&&map[ny][nx]!='#') { int d; 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)); } } } return dist[gy][gx]; } int main() { while(cin>>N>>M) { for(int i=0; i<N; i++) { for(int j=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; } } } int exist=bfs(sy,sx); if(exist==INF) { cout<<"Poor ANGEL has to stay in the prison all his life."<<endl; } else { cout<<exist<<endl; } } return 0; }
代码二:
#include"iostream" #include"queue" using namespace std; const int INF=0x30303030; const int MAX_N=205; int N, M; char map[MAX_N][MAX_N]; int sy, sx; int gx, gy; int dx[4]={1, 0, -1, 0}; int dy[4]={0, 1, 0, -1}; int d[MAX_N][MAX_N]; struct node{ int y; int x; int step; node(int y, int x, int step) { this->y=y; this->x=x; this->step=step; } friend bool operator<(node no1, node no2) { return no1.step > no2.step; } }; void dfs() { for(int i=0; i<N; i++) { for(int j=0; j<M; j++) { d[i][j]=INF; } } int ans; bool exist=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(int i=0; i<4; i++) { int ny=now.y+dy[i]; int nx=now.x+dx[i]; if(0<=ny&&ny<N&&0<=nx&&nx<M&&map[ny][nx]!='#') { int dist; 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 has to stay in the prison all his life."<<endl; } } int main() { while(cin>>N>>M) { for(int i=0; i<N; i++) { for(int j=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; }
相关文章推荐
- Android JNI打印Log
- C++之 typedef
- 第五章:循环
- [python]学习笔记5-函数参数类型
- 深入理解OAuth2.0协议
- 简述UIView、UIWindow和CALayer的理解
- Unix整理笔记——Unix基础——里程碑
- 十进制转IP地址的简单处理方案
- RKAndroidTool工具的各项image详解(RK2918版本)
- Interlocked(续)
- Apache源码分析
- 高仿煎蛋iOS项目基础配置(2)
- Tiny6410学习成果—视频采集小车(端程序)
- LAMP环境搭建
- 栈的链式实现(C语言描述)
- Unity优化大全(九)之 Memory - Unity3D内部的内存
- IOS开发错误提示原因集合-----长期更新
- 【UI初级 连载一】------iPhone开发入门
- 正则表达式grep、egrep、fgrep
- 使用adb更换Android媒体文件