Monsters
题目描述
You and some monsters are in a labyrinth. When taking a step to some direction in the labyrinth, each monster may simultaneously take one as well. Your goal is to reach one of the boundary squares without ever sharing a square with a monster.
Your task is to find out if your goal is possible, and if it is, print a path that you can follow. Your plan has to work in any situation; even if the monsters know your path beforehand.输入
The first input line has two integers n and m: the height and width of the map.
After this there are n lines of m characters describing the map. Each character is . (floor), # (wall), A (start), or M (monster). There is exactly one A in the input.
Constraints
1 ≤ n,m ≤ 1000输出
First print "YES" if your goal is possible, and "NO" otherwise.
If your goal is possible, also print an example of a valid path (the length of the path and its description using characters D, U, L, and R). You can print any path, as long as its length is at most n * m steps.样例输入
5 8
########
#M..A..#
#.#.M#.#
#M#..#..
#.######样例输出
YES
5
RRDDR
题目大意:人和怪物同步移动,要求每次移动的过程中都不能和怪物处在同一个格子。问人能否到达边界
思路:开两次bfs,先对怪物,记录怪物走到每一个格子的步数,再对人,人走到每一个格子时,比较人需要的步数和怪物需要的步数,如果怪物走不到或者人比怪物先到,就可以走,否则就不能走这个格子。
注意一个细节,在走的时候,由于二者的路不能交叉,所以只有=='.'才能走,而不是 ! ='#'
代码
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const int N=1010;
char a[N][N];
int ss[N][N];
int step[N][N];
bool f[N][N];
int fx[5]={0,1,0,-1,0};
int fy[5]={0,0,1,0,-1};
char c[5]={' ','D','R','U','L'};
char dir[N][N];
pair<int,int>parent[N][N];
int main() {ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int n,m;cin>>n>>m;queue<pair<int,int>>q;int sx,sy;memset(ss,-1,sizeof(ss));for (int i=1;i<=n;i++){for (int j=1;j<=m;j++){cin>>a[i][j];if(a[i][j]=='M'){q.push({i,j});f[i][j]=true;ss[i][j]=0;}else if (a[i][j]=='A'){sx=i;sy=j;}}}if (sx==1||sx==n||sy==1||sy==m){cout<<"YES\n0";return 0;}while(!q.empty()){int x=q.front().first,y=q.front().second;int s=ss[x][y];q.pop();int tx,ty;for (int i=1;i<=4;i++){tx=x+fx[i];ty=y+fy[i];if (tx<1||tx>n||ty<1||ty>m)continue;if (!f[tx][ty]&&a[tx][ty]=='.'){ q.push({tx,ty});f[tx][ty]=true;ss[tx][ty]=s+1;}}}int ex,ey;q.push({sx,sy});a[sx][sy]='#'; step[sx][sy]=0;bool ok=false;while(!q.empty()){int x=q.front().first,y=q.front().second;int s=step[x][y];q.pop();int tx,ty;for (int i=1;i<=4;i++){tx=x+fx[i];ty=y+fy[i];if (tx<1||tx>n||ty<1||ty>m)continue;if (a[tx][ty]=='.'){ if (ss[tx][ty]!=-1&&(s+1)>=ss[tx][ty]){//怪物先到 a[tx][ty]='#';continue; }a[tx][ty]='#';step[tx][ty]=s+1;parent[tx][ty]={x,y};dir[tx][ty]=c[i];if (tx==1||tx==n||ty==1||ty==m){ok=true;ex=tx,ey=ty;break;}q.push({tx,ty});}}}if (ok){cout<<"YES\n"<<step[ex][ey]<<"\n";vector<char>res;int cx=ex,cy=ey;while(cx!=sx||cy!=sy){res.push_back({dir[cx][cy]});int tx=cx,ty=cy;cx=parent[tx][ty].first;cy=parent[tx][ty].second;}for (auto it=res.rbegin();it!=res.rend();it++)cout<<*it;}elsecout<<"NO\n";
}
(啊啊啊,气死我了,又双叒看错题了,卡了一下午,英文题目真的看不懂一点)