## Gym - 101755H

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.

Input
The first line contains three non-negative integers n, m and d (2 ≤ n·m ≤ 200000, 0 ≤ d ≤ 200000) — the size of the map and the maximal distance at which monsters are dangerous.

Each of the next n lines contains m characters. These characters can be equal to «.», «M», «S» and «F», which denote empty cell, cell with monster, start cell and finish cell, correspondingly. Start and finish cells are empty and are presented in the input exactly once.

Output
If it is possible to get alive from start cell to finish cell, output minimal number of steps required to do it. Otherwise, output «-1».

m<=200000),所以可以用一维数组在表示每个格子

``````#include <cstdio>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
queue <int> X,Y,XX,YY;
int r;
bool sym;
int d;
int n,m,L,sx,sy,ex,ey;
int ans=-1;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
bool symt=false;
int S=1;
void bfs1()
{
while (!XX.empty())
{
int x=XX.front();
int y=YY.front();
XX.pop();YY.pop();
for (int i=0;i<4;i++)
{
int xx=x+dx[i];
int yy=y+dy[i];
if (xx<1 || xx>n || yy<1 || yy>m || d[x*m+y]==0) continue;
if (d[x*m+y]-1>=d[xx*m+yy])
{
d[xx*m+yy]=d[x*m+y]-1;
if (!sym[xx*m+yy])
{
sym[xx*m+yy]=true;
XX.push(xx);
YY.push(yy);
}
}
}
}
}
void BFS()
{
X.push(sx);
Y.push(sy);
sym[sx*m+sy]=1;
while (!X.empty())
{
int x=X.front();
int y=Y.front();
X.pop();Y.pop();
for (int i=0;i<4;i++)
{
int xx=x+dx[i];
int yy=y+dy[i];
if (xx<1 || xx>n || yy<1 || yy>m || sym[xx*m+yy]!=0) continue;
X.push(xx);
Y.push(yy);
sym[xx*m+yy]=1;
r[xx*m+yy]=r[x*m+y]+1;
if (xx==ex && yy==ey)
{
ans=r[xx*m+yy];
return;
}
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&L);
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
{
char ch;
cin>>ch;
if (ch=='S')
{
sx=i;
sy=j;

}
if (ch=='F')
{
ex=i;
ey=j;
}
if (ch=='M')
{
XX.push(i);
YY.push(j);
d[i*m+j]=L;
sym[i*m+j]=true;
}
}
bfs1();
if (sym[sx*m+sy]!=0 || sym[ex*m+ey]!=0) ans=-1;
else BFS();
printf("%d\n",ans);
}
``````