您的位置:首页 > 其它

HDU 1180 诡异的楼梯(bfs+判断)

2017-01-12 21:37 423 查看

注意:

1,楼梯不会连续出现,避免考虑很多楼梯连着的复杂情况。

2,存在等在楼梯前,然后走楼梯的情况。

3,考虑过了楼梯直接就是终点的情况。

#include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>

using namespace std;

char s[22];
int sx,sy;

int v[30][30];

int d[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};//方向分量

struct node{
int x,y,t;
int flag = 0;
node(){}
node(int x,int y,int t,int flag){
this->x = x,this->y = y,this->t = t,this->flag = flag;
}
};

int bfs(int ii,int jj){
node temp(ii,jj,0,0);
int ans = -100;
queue<node> q;
q.push(temp);
while(!q.empty()){
temp = q.front();
q.pop();
if(temp.flag == 1){
temp.t++;
temp.flag = 0;
if(v[temp.x][temp.y] == 666)
return temp.t;
q.push(temp);
continue;
}
else if(v[temp.x][temp.y] == 666)
return temp.t;

for(int i = 0;i < 4;i++){
int a = temp.x + d[i][0],b = temp.y + d[i][1];
if(v[a][b] == 1){
v[a][b] = 0;
q.push(node(a,b,temp.t+1,0));
}
else if(v[a][b] == 2 || v[a][b] == -2){// 此格是楼梯

int t1 = v[a][b];
if(temp.t & 1)
t1 = -v[a][b];
int aa = a + d[i][0],bb = b + d[i][1];

int &t2 = v[aa][bb];
if(t1 == 2 && t2 != 0){
if(t2 == 1)
t2 = 0;
if(i < 2){// 方向为竖
q.push(node(aa,bb,temp.t+1,0));
}
else{
q.push(node(aa,bb,temp.t+1,1));
}
}
else if(t1 == -2 && t2 != 0){
if(t2 == 1)
t2 = 0;
if(i > 1){// 方向为横
q.push(node(aa,bb,temp.t+1,0));
}
else{
q.push(node(aa,bb,temp.t+1,1));
}
}
}
else if(v[a][b] == 666){
return temp.t+1;
}
}
}
return -1;
}

int main(){
int ans;
int m,n;
while(scanf("%d%d",&m,&n) != EOF){
memset(v,0,sizeof(v));
for(int i = 1;i <= m;i++){
scanf("%s",s);
for(int j = 0;j < n;j++){
if(s[j] == 'S'){
sx = i,sy = j+1;
v[i][j+1] = 0;
}
else if(s[j] == 'T'){
v[i][j+1] = 666;
}
else if(s[j] == '.'){
v[i][j+1] = 1;
}
else if(s[j] == '|'){
v[i][j+1] = 2;
}
else if(s[j] == '-'){
v[i][j+1] = -2;
}
}
}
ans = bfs(sx,sy);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: