HDU 1180 诡异的楼梯(BFS,用优先队列过)
2015-09-25 16:56
399 查看
#include<stdio.h> #include<string.h> #include<queue> #include<algorithm> using namespace std; char map[25][25]; int PRE[25][25]; int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}}; int m,n; int sx,sy,ex,ey; struct node { int x; int y; int step; bool operator<(const node &s)const { return step>s.step; } }; int bfs() { struct node now,pre; priority_queue<node>Q; pre.x=sx; pre.y=sy; pre.step=0; Q.push(pre); while(!Q.empty()) { pre=Q.top(); Q.pop(); if(pre.x==ex&&pre.y==ey&&map[pre.x][pre.y]=='T') { return pre.step; } for(int i=0; i<4; i++) { now.x=pre.x+dir[i][0]; now.y=pre.y+dir[i][1]; now.step=pre.step+1; if(map[now.x][now.y]=='|')//当前走到的地理位置 { if(now.x==pre.x&&((pre.step)&1==0))//左右走的时候 { now.step+=1;//停留一下,等它回复的时候,就可以走了 } if(now.y==pre.y&&((pre.step)&1==1))//上下走的时候 { now.step+=1;//停留一下,等它回复的时候,就可以走了 } now.x=now.x+dir[i][0]; now.y=now.y+dir[i][1]; } if(map[now.x][now.y]=='-') { if(now.x==pre.x&&((pre.step)&1==1))//左右走的时候 { now.step+=1; } if(now.y==pre.y&&((pre.step)&1==0))//上下走的时候 { now.step+=1; } now.x=now.x+dir[i][0]; now.y=now.y+dir[i][1]; } if(now.x>=0&&now.x<m&&now.y>=0&&now.y<n&&PRE[now.x][now.y]<now.step&&(map[now.x][now.y]=='.'||map[now.x][now.y]=='S'||map[now.x][now.y]=='T'))//判断路径是否合法 { PRE[now.x][now.y]=now.step;//记录上一步的步数,来给下一步都的时候判断用,当前一步小于后一步,可以走,否则不可以走 Q.push(now); } else { continue; } } } return -1; } int main() { while(scanf("%d%d",&m,&n)!=EOF) { memset(PRE,0,sizeof(PRE)); int i,j; for(i=0; i<m; i++) { scanf("%s",map[i]); for(j=0; j<n; j++) { if(map[i][j]=='S') { sx=i; sy=j; } if(map[i][j]=='T') { ex=i; ey=j; } } } int t=bfs(); printf("%d\n",t); } return 0; }
相关文章推荐
- delphi android Toast
- wampserver环境套装
- Java基础知识强化90:Date类之Data类中日期和毫秒相互转换
- Magicodes.WeiChat——自定义knockoutjs template、component实现微信自定义菜单
- 异常处理原则
- List,set,Map 的用法和区别等
- oracle 树查询
- 上传文件 隐藏input type="file",用text显示
- 文件列表前面显示的✚和﹄的方法
- K-均值聚类算法(K-means)
- htmlunit简单翻译
- nginx源代码安装make报错
- acm进阶计划
- K-均值聚类算法(K-means)
- 矩阵的之字型遍历
- 修复APP 适配 ios9
- 设计模式 - 原型模式(Prototype)
- 最简单的3个数字小到大排序
- shell脚本1.0
- Nginx+Tomcat实现动静分离