搜索--曼哈顿距离

Last night, little erriyue had a horrible nightmare. He dreamed that he and his girl friend were trapped in a big maze separately. More terribly, there are two ghosts in the maze. They will kill the people. Now little erriyue wants to know if he could find his girl friend before the ghosts find them. 
You may suppose that little erriyue and his girl friend can move in 4 directions. In each second, little erriyue can move 3 steps and his girl friend can move 1 step. The ghosts are evil, every second they will divide into several parts to occupy the grids within 2 steps to them until they occupy the whole maze. You can suppose that at every second the ghosts divide firstly then the little erriyue and his girl friend start to move, and if little erriyue or his girl friend arrive at a grid with a ghost, they will die. 
Note: the new ghosts also can devide as the original ghost. 

Input

The input starts with an integer T, means the number of test cases. 

Each test case starts with a line contains two integers n and m, means the size of the maze. (1The next n lines describe the maze. Each line contains m characters. The characters may be: 
‘.’ denotes an empty place, all can walk on. 
‘X’ denotes a wall, only people can’t walk on. 
‘M’ denotes little erriyue 
‘G’ denotes the girl friend. 
‘Z’ denotes the ghosts. 

It is guaranteed that will contain exactly one letter M, one letter G and two letters Z. 


Output

Output a single integer S in one line, denotes erriyue and his girlfriend will meet in the minimum time S if they can meet successfully, or output -1 denotes they failed to meet.Sample Input

3
5 6
XXXXXX
XZ..ZX
XXXXXX
M.G...
......
5 6
XXXXXX
XZZ..X
XXXXXX
M.....
..G...

10 10
..........
..X.......
..M.X...X.
X.........
.X..X.X.X.
.........X
..XX....X.
X....G...X
...ZX.X...
...Z..X..X
Sample Output
1
1
-1

大致题意:一男一女被分隔在一个迷宫中 迷宫里面有两只鬼 每秒分裂出可以占据距离他两个步数的方格的位置 分身可以继续分裂 鬼会杀死人 问男女相遇的最小时间 若不能相遇 输出-1

一开始以为是道很水的BFS 直接把男女鬼都扔进队列里面 修改一下他们的go函数 但是后来发现男走的3步是不能越墙走的 于是把男女分开两个队列(粗心了又) 但是TLE了 看了下别人的做法他们都没有把鬼拿去做BFS 而是算男女每次走的时候的点和鬼的曼哈顿距离是否小于2乘以时间 这样时间就大大减少了

因为那个鬼每次都会把与自身曼哈顿距离小于等于2的格子占领 这样一开始你人和鬼的曼哈顿距离是不能小于等于2*k的话 下一次鬼分裂的时候 你就要和原鬼曼哈顿距离为2的新鬼保持2的曼哈顿距离 所以每次你只要判是否为原鬼曼哈顿距离乘时间就行了 很巧妙

后来看了一下曼哈顿距离 发现很多广搜 其实都可以用曼哈顿距离代替去算来减少复杂度 比如这篇博客:

https://blog.csdn.net/cqbzlytina/article/details/75162183

在求了两个连通块后直接枚举曼哈顿距离就行了 不用每个点都跑一次BFS

又学到了一个新东西 

最近很多事做 刷题少了 时间复杂度都不会算了。。。

你可能感兴趣的:(算法竞赛)