题目描述:点击进入
思路
这里的难点主要是搜索过程中遇到 “ | ” 或者 “ - ” 的处理。 我的处理是,遇见了,就直接越过去,直接存它的下一个点(当然了,还得判断下一个点是否越界以及走过或者是墙壁); 如果当时楼梯方向正好和你搜索的方向相同,那步数+1; 如果不同,那么等一秒再过去,就是步数+2; 关于楼梯方向和搜索的方向是否相同的判断,还是看代码吧~~~~~
代码
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std
;
const int d
[4][2]={1,0,-1,0,0,1,0,-1};
char mp
[110][110];
bool vis
[110][110];
int n
,m
,cnt
;
struct node
{
int x
;
int y
;
int step
;
}tmp
;
int bfs(int x
,int y
)
{
tmp
.x
=x
;
tmp
.y
=y
;
tmp
.step
=0;
vis
[x
][y
]=1;
queue
<node
>q
;
q
.push(tmp
);
while(q
.size())
{
node cur
=q
.front();
q
.pop();
if(mp
[cur
.x
][cur
.y
]=='T') return cur
.step
;
for(int i
=0;i
<4;i
++)
{
int xx
=cur
.x
+d
[i
][0];
int yy
=cur
.y
+d
[i
][1];
if(xx
<=0||yy
<=0||xx
>n
||yy
>m
) continue;
if(mp
[xx
][yy
]=='*'||vis
[xx
][yy
]) continue;
if(mp
[xx
][yy
]=='|')
{
if(d
[i
][0]==0)
{
if(cur
.step
&1) tmp
.step
=cur
.step
+1;
else tmp
.step
=cur
.step
+2;
xx
=cur
.x
+d
[i
][0]*2;
yy
=cur
.y
+d
[i
][1]*2;
if(xx
<=0||yy
<=0||xx
>n
||yy
>m
) continue;
if(mp
[xx
][yy
]=='*'||vis
[xx
][yy
]) continue;
}
else
{
if(cur
.step
&1) tmp
.step
=cur
.step
+2;
else tmp
.step
=cur
.step
+1;
xx
=cur
.x
+d
[i
][0]*2;
yy
=cur
.y
+d
[i
][1]*2;
if(xx
<=0||yy
<=0||xx
>n
||yy
>m
) continue;
if(mp
[xx
][yy
]=='*'||vis
[xx
][yy
]) continue;
}
}
else if(mp
[xx
][yy
]=='-')
{
if(d
[i
][0]==0)
{
if(cur
.step
&1) tmp
.step
=cur
.step
+2;
else tmp
.step
=cur
.step
+1;
xx
=cur
.x
+d
[i
][0]*2;
yy
=cur
.y
+d
[i
][1]*2;
if(xx
<=0||yy
<=0||xx
>n
||yy
>m
) continue;
if(mp
[xx
][yy
]=='*'||vis
[xx
][yy
]) continue;
}
else
{
if(cur
.step
&1) tmp
.step
=cur
.step
+1;
else tmp
.step
=cur
.step
+2;
xx
=cur
.x
+d
[i
][0]*2;
yy
=cur
.y
+d
[i
][1]*2;
if(xx
<=0||yy
<=0||xx
>n
||yy
>m
) continue;
if(mp
[xx
][yy
]=='*'||vis
[xx
][yy
]) continue;
}
}
else
{
tmp
.step
=cur
.step
+1;
}
vis
[xx
][yy
]=1;
tmp
.x
=xx
;
tmp
.y
=yy
;
q
.push(tmp
);
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&n
,&m
))
{
int ans
=0;
memset(vis
,0,sizeof(vis
));
for(int i
=1;i
<=n
;i
++)
{
scanf("%s",mp
[i
]+1);
}
for(int i
=1;i
<=n
;i
++)
{
for(int j
=1;j
<=m
;j
++)
{
if(mp
[i
][j
]=='S')
{
ans
=bfs(i
,j
);
break;
}
}
}
printf("%d\n",ans
);
}
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-43603.html