Safe Path/GYM 101755H/BFS
题目
You play a new RPG. The world map in it is represented by a grid of n × m cells. Any playing character staying in some cell can move from this cell in four directions — to the cells to the left, right, forward and back, but not leaving the world map.
Monsters live in some cells. If at some moment of time you are in the cell which is reachable by some monster in d steps or less, he immediately runs to you and kills you.
You have to get alive from one cell of game field to another. Determine whether it is possible and if yes, find the minimal number of steps required to do it.
题目来源:GYM 101755H
题目链接
题意
有一个n*m的迷宫,先需要从S点走到F点,迷宫中有小怪,当有人走到距离它d格内时小怪会发起攻击,求S到F的最小步数,如果无法到达输出-1。
解法
先用BFS对小怪能攻击的格标记,然后再跑一遍BFS求最小步数。需要注意题目只给出n*m<=200000,所以需要将二维图转化为一维的。
代码:
#include <cstring>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int n,m,ans,d,sx,sy,ex,ey;
bool f[200010],flag;
char st[200010];
queue <int> X,Y,T,qx,qy;
void bfs1()
{
int x,y,t,nx,ny;
while(!qx.empty())
{
x=qx.front();y=qy.front();t=T.front();
qx.pop();qy.pop();T.pop();
for(int i=0;i<4;i++)
{
nx=x+dx[i];
ny=y+dy[i];
if (nx<1 || nx>n || ny<1 || ny>m ||f[(nx-1)*m+ny] || t>=d) continue;
qx.push(nx);
qy.push(ny);
T.push(t+1);
f[(nx-1)*m+ny]=true;
}
}
}
void bfs(int sx,int sy)
{
X.push(sx);
Y.push(sy);
while (!T.empty()) T.pop();
T.push(0);
int x,y,t,nx,ny;
if (f[(sx-1)*m+sy]) return;
f[(sx-1)*m+sy]=true;
while(!X.empty())
{
x=X.front();y=Y.front();t=T.front();
X.pop();Y.pop();T.pop();
for(int i=0;i<4;i++)
{
nx=x+dx[i];
ny=y+dy[i];
if (nx<1 || nx>n || ny<1 || ny>m || f[(nx-1)*m+ny]) continue;
X.push(nx);
Y.push(ny);
T.push(t+1);
f[(nx-1)*m+ny]=true;
if(nx==ex && ny==ey) ans=t+1,flag=true;
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&d);
for (int i=1;i<=n;i++)
{
scanf("%s",st);
for (int j=0;j<m;j++)
{
if (st[j]=='M')
{
qx.push(i);qy.push(j+1);f[(i-1)*m+j+1]=true;T.push(0);
}
if (st[j]=='S')
{
sx=i;sy=j+1;
}
if (st[j]=='F')
{
ex=i;ey=j+1;
}
}
}
bfs1();
flag=false;
bfs(sx,sy);
if (flag) printf("%d",ans); else printf("-1");
return 0;
}