1G: bfs

安稳与你 提交于 2020-03-12 17:26:21

传送门

题目

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.InputThe 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.OutputIf it is possible to get alive from start cell to finish cell, output minimal number of steps required to do it. Otherwise, output «-1».Examples

Input

5 7 1
S.M...M
.......
.......
M...M..
......F




Output

12




Input

7 6 2
S.....
...M..
......
.....M
......
M.....
.....F




Output

11




Input

7 6 2
S.....
...M..
......
......
.....M
M.....
.....F




Output

-1




Input

4 4 2
M...
.S..
....
...F




Output

-1

题目翻译

您在玩一个新的RPG。其中的世界地图由n×m个单元的网格表示。停留在某个单元格中的任何游戏角色都可以从该单元格向四个方向移动-移至左侧,右侧,向前和向后的单元格,但不会离开世界地图。怪物生活在一些细胞中。如果在某个时刻,您处于某个怪物可以d步或更短距离到达的牢房中,他会立即冲向您并杀死您。您必须从一个游戏领域的另一个单元活下来。确定是否可能,如果可以,请找到执行此操作所需的最少步骤。输入值第一行包含三个非负整数n,m和d(2≤n·m≤200000,0≤d≤200000)—地图的大小和怪物危险的最大距离。接下来的n行中的每行包含m个字符。这些字符可以等于«。»,«M»,«S»和«F»,分别表示空单元格,带有怪兽的单元格,开始单元格和结束单元格。开始和结束单元格为空,并且在输入中仅显示一次。输出量如果可以从起始单元格到结束单元格恢复活力,则输出执行此步骤所需的最少步骤。否则,输出«-1»。

解法

求最少步数,显然是用bfs,值得一提的是它给定的n和m的范围是2≤n·m≤200000,所以直接开_map[200000][200000]会炸, 可以开个一维数组,坐标转化一下就好了,或者在输入n和m后再创建数组
(反正200000又不会爆)

代码

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

int dir[4][2] = {1,0, 0,1, -1,0, 0,-1};
int main()
{
	int n, m, d;
    	cin >> n >> m >> d;
     	char _map[n+5][m+5];
	bool vis[n+5][m+5];
	memset(vis, 0, sizeof(vis));
 	memset(_map, 0, sizeof(_map));
	
	 for(int i=1; i<=n; ++i) {
 		 for(int j=1; j<=m; ++j) {
  			 cin >> _map[i][j];
 	 	}
	 }
	 queue <int> xx, yy, dd;
	 int sx, sy, gx, gy;
	 for(int i=1; i<=n; ++i) {
 	 	for(int j=1; j<=m; ++j) {
  	 		if(_map[i][j]=='S') {
  	  			sx = i;
  	  			sy = j;
  	 		}
  	 		if(_map[i][j]=='F') {
		  	  gx = i;
		  	  gy = j;
		  	 }
		  	if(_map[i][j] =='M') {
				    xx.push(i);
				    yy.push(j);
				    vis[i][j] = 1;
				    dd.push(d);
			 }
		}
	 }

	return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!