版权声明:那个,最起码帮我加点人气吧,署个名总行吧 https://blog.csdn.net/qq_41670466/article/details/85088072
题意就是给你一个图,图里'.'表示可走,’x'表示墙,‘z'表示怪物,怪物每秒可以向外分裂两个单位,现在你和你的女朋友被困在这个地图里,你每秒可以移动三个单位,你女朋友每秒可以移动一个单位,每一秒,怪物先分裂,然后你们才开始移动,问:你们是否可以在被鬼怪抓到前,相遇?
思路:双向bfs 一个广搜男生的路线,另一个广搜女生的路线,对于男生每秒可以移动三个单位意思是最多移动三个单位,哎,我当初就是这一点没读懂,一直wa,对于这个点的实现是分三次bfs,每一次都只移动一个单位,每搜一次都判断会不会和女生相遇
对于与鬼怪的相遇问题:处理方法是计算与两个怪物的哈夫曼距离和2*当前进行的回合数进行比较,如果小于则代表处于鬼怪的网格之中,那么这个路不通,continue; 剩下的就没什么了。
啊,每次碰到这种不知道是题意描述不清还是自己理解能力太差导致久久不能ac的题内心总是。。。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
struct Node
{
int x, y;
}Mon[2];
int step = 0;
int m_x,m_y,g_x, g_y;
int n, m;
char maze[810][810];
int used[2][810][810];
int dir[4][2] = { 1,0,-1,0,0,1,0,-1 };
queue<Node>que[2];
int check(Node a)
{
if (a.x < 0 || a.y < 0 || a.x >= n || a.y >= m) return 0;
if (maze[a.x][a.y] == 'X') return 0;
if ((abs(a.x - Mon[0].x) + abs(a.y - Mon[0].y)) <= 2 * step) return 0;
if ((abs(a.x - Mon[1].x) + abs(a.y - Mon[1].y)) <= 2 * step) return 0;
return 1;
}
int bfs(int w)
{
int sum = que[w].size();
while (sum--)
{
Node next = que[w].front();
que[w].pop();
if(check(next)==0) continue;
for (int i = 0; i < 4; i++)
{
Node tem;
tem.x = next.x + dir[i][0];
tem.y = next.y + dir[i][1];
if (check(tem) == 0) continue;
if (used[w][tem.x][tem.y] == 0)
{
if (used[w ^ 1][tem.x][tem.y] == 1) return 1;
used[w][tem.x][tem.y] = 1;
que[w].push(tem);
}
}
}
return 0;
}
int solve()
{
while (!que[0].empty()) que[0].pop();
while (!que[1].empty()) que[1].pop();
Node tem;
tem.x = m_x;
tem.y = m_y;
que[0].push(tem);
tem.x = g_x;
tem.y = g_y;
que[1].push(tem);
memset(used, 0, sizeof(used));
used[0][m_x][m_y]=used[1][g_x][g_y]=1;
step = 0;
while (!que[0].empty() || !que[1].empty())
{
step++;
if (bfs(0) == 1)return step;
if (bfs(0) == 1)return step;
if (bfs(0) == 1)return step;
if (bfs(1) == 1)return step;
}
return -1;
}
int main()
{
// ios::sync_with_stdio(false);
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d %d", &n,&m);
int cnt = 0;
for(int i=0;i<n;i++)
scanf("%s",maze[i]);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
//cin >> maze[i][j]; //scanf("%c",&maze[i][j]);
if (maze[i][j] == 'G')
{
g_x = i;
g_y= j;
}
else if (maze[i][j] == 'M')
{
m_x = i;
m_y= j;
}
else if (maze[i][j] == 'Z')
{
Mon[cnt].x = i;
Mon[cnt++].y = j;
}
}
}
printf("%d\n", solve());
}
system("pause");
return 0;
}