题意:问两个迷宫是否存在公共最短路。
题解:两个反向bfs建立层次图,一遍正向bfs寻找公共最短路
#include<cstdio> #include<cstring> #include<queue> using namespace std; const int maxn = 500+1; int d1[maxn][maxn]; int d2[maxn][maxn]; char g1[maxn][maxn]; char g2[maxn][maxn]; int n,m; struct node{ int x,y; node(int X = 0, int Y = 0){ x = X; y = Y; } }; int dx[] = {1,-1,0,0}; int dy[] = {0,0,1,-1}; //1,1 void rbfs(int id) { char (*G)[maxn]; int (*vis)[maxn]; if(id == 1) G = g1, vis = d1; else G = g2, vis = d2; memset(vis,-1,sizeof(d1)); queue<node>q; node u(n-1,m-1); q.push(u); vis[u.x][u.y] = 0; while(q.size()){ u = q.front();q.pop(); if(u.x == 0 && u.y == 0) return; for(int i = 0; i < 4; i++){ int nx = u.x + dx[i], ny = u.y + dy[i]; if(nx>=0&&nx<n&&ny>=0&&ny<m&&G[nx][ny]!='#'&&!~vis[nx][ny]){ vis[nx][ny] = vis[u.x][u.y]+1; q.push(node(nx,ny)); } } } } bool vis[maxn][maxn]; bool bfs() { if(d1[0][0] != d2[0][0] )return false; memset(vis,0,sizeof(vis)); queue<node>q; q.push(node(0,0)); int tx = n-1, ty = m-1; while(q.size()){ node &u = q.front(); if(u.x == tx && u.y == ty) return true; for(int i = 0; i < 4; i++){ int nx = u.x + dx[i], ny = u.y + dy[i]; if(nx>=0&&nx<n&&ny>=0&&ny<m&& d1[nx][ny] == d1[u.x][u.y] - 1 && d2[nx][ny] == d2[u.x][u.y] - 1 && !vis[nx][ny]){ vis[nx][ny] = 1; q.push(node(nx,ny)); } } q.pop(); } return false; } int main() { // freopen("in.txt","r",stdin); scanf("%d%d",&n,&m); for(int i = 0; i < n; i++) scanf("%s",g1[i]); for(int i = 0; i < n; i++) scanf("%s",g2[i]); rbfs(1); rbfs(2); printf("%s ",bfs()?"YES":"NO"); return 0; }