您的位置:首页 > 其它

【BFS&&优先队列】HDU 1180 诡异的楼梯

2014-08-10 15:09 525 查看
 

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1180

 

 

 

设梯子状态 |为0,—为1
利用(初始状态+步数)%2算出当前梯子状态


 

当遇到梯子,若当前不能走过则到对面且步数加2,[b]若当前能走过则到对面且步数加1,利用优先队列进行BFS[/b]

 

#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;

struct node{
friend bool operator< (node n1, node n2)
{
return n1.step > n2.step;
}
int x,y;
int step;
};

priority_queue<node> q;
int n,m;
char map[220][220];
int vis[220][220];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};

bool jud(int x,int y){
if(x>=0&&x<n&&y>=0&&y<m&&map[x][y]!='*'&&!vis[x][y])
return true;
return false;
}

int bfs(node start){
while(!q.empty())q.pop();
node now,next;
q.push(start);
int i;
while(!q.empty()){
now=q.top();
q.pop();
if(map[now.x][now.y]=='T')
return now.step;
for(i=0;i<4;++i){
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];

if(map[next.x][next.y]=='-'||map[next.x][next.y]=='|'){
int stu=(map[next.x][next.y]=='|')?0:1;//|=0,-=1;

if((now.step+stu)%2==1){//梯子横
if(next.x==now.x){//横向走
next.step=now.step+1;
next.y+=dir[i][1];
}else{//纵向走
next.step=now.step+2;
next.x+=dir[i][0];
}
}else{
if(next.x==now.x){//横向走
next.step=now.step+2;
next.y+=dir[i][1];
}else{//纵向走
next.step=now.step+1;
next.x+=dir[i][0];
}
}

}
else
next.step=now.step+1;

if(!jud(next.x,next.y))continue;
vis[next.x][next.y]=1;
q.push(next);
}
}
return -1;
}

int main(){
int i,j;
int ans;
node start;
while(scanf("%d%d\n",&n,&m)!=EOF){
ans=-1;
memset(vis,0,sizeof(vis));
for(i=0;i<n;++i){
for(j=0;j<m;++j){
scanf("%c",&map[i][j]);
}
getchar();
}
for(i=0;i<n;++i){
for(j=0;j<m;++j){
if(map[i][j]=='S'){
start.x=i,start.y=j;
start.step=0;
ans=bfs(start);
}
}
}

printf("%d\n",ans);

}
return 0;
}


 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  搜索