题意:给你两幅图,判断一下两幅图是否有公共的最短路径,从左上角走到右下角,有的话输出YES,否则输出NO
思路:
首先把两幅图合在一起搜一遍,看是否有公共的路径走到右下角(右下角不一定可达),有的话,记下步数,没有的话,直接输出NO;
然后,搜一遍第一幅图,记下到达右下角的最短步数(如果不可达,第一步之后就结束了);
再搜一遍第二幅图,记下到达右下角的最短步数;
最后比较这三个步数是否相等,都相等,则输出YES,否则输出NO;
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<cstdlib>
using namespace std;
struct node
{
char ch;
int x,y;
int step;
};
struct node maz1[509][509],maz2[509][509];//第一幅图,第二幅图
bool vis[509][509];
int n,m;
int dir[4][2] = {0,-1,-1,0,0,1,1,0};
void BFS()//两幅图合在一起搜一遍
{
int i;
struct node a,b;
queue<node>q;
while (!q.empty())
q.pop();
memset(vis,false,sizeof(vis));
maz1[0][0].step = 0;
maz2[0][0].step = 0;
vis[0][0] = true;
q.push(maz1[0][0]);
while (!q.empty())
{
a = q.front();
q.pop();
for (i = 0; i < 4; ++i)
{
b.x = a.x + dir[i][0];
b.y = a.y + dir[i][1];
if (b.x < 0 || b.x >= n || b.y < 0 || b.y >= m)
continue;
if (maz1[b.x][b.y].ch == '.' && maz2[b.x][b.y].ch == '.' && !vis[b.x][b.y])//合在一起
{
b.step = a.step + 1;
maz1[b.x][b.y].step = a.step + 1;
maz2[b.x][b.y].step = a.step + 1;
vis[b.x][b.y] = true;
if (b.x == n-1 && b.y == m-1)
return ;
q.push(b);
}
}
}
return ;
}
void BFS1()//搜一遍第一幅图
{
int i;
struct node a,b;
queue<node>q;
while (!q.empty())
q.pop();
memset(vis,false,sizeof(vis));
maz1[0][0].step = 0;
q.push(maz1[0][0]);
vis[0][0] = true;
while (!q.empty())
{
a = q.front();
q.pop();
for (i = 0; i < 4; ++i)
{
b.x = a.x + dir[i][0];
b.y = a.y + dir[i][1];
if (b.x < 0 || b.x >= n || b.y < 0 || b.y >= m)
continue;
if (maz1[b.x][b.y].ch == '.' && !vis[b.x][b.y])
{
vis[b.x][b.y] = true;
b.step = a.step + 1;
maz1[b.x][b.y].step = a.step + 1;
if (b.x == n-1 && b.y == m-1)
return ;
q.push(b);
}
}
}
}
void BFS2()//搜一遍第二幅图
{
int i;
struct node a,b;
queue<node>q;
while (!q.empty())
q.pop();
memset(vis,false,sizeof(vis));
maz2[0][0].step = 0;
q.push(maz2[0][0]);
vis[0][0] = true;
while (!q.empty())
{
a = q.front();
q.pop();
for (i = 0; i < 4; ++i)
{
b.x = a.x + dir[i][0];
b.y = a.y + dir[i][1];
if (b.x < 0 || b.x >= n || b.y < 0 || b.y >= m)
continue;
if (maz2[b.x][b.y].ch == '.' && !vis[b.x][b.y])
{
vis[b.x][b.y] = true;
b.step = a.step + 1;
maz2[b.x][b.y].step = a.step + 1;
if (b.x == n-1 && b.y == m-1)
return ;
q.push(b);
}
}
}
}
int main()
{
int i,j;
while (~scanf("%d%d",&n,&m))
{
for (i = 0; i < n; ++i)
{
for (j = 0; j < m; ++j)
{
cin>>maz1[i][j].ch;
maz1[i][j].x = i;
maz1[i][j].y = j;
}
}//存第一幅图
for (i = 0; i < n; ++i)
{
for (j = 0; j < m; ++j)
{
cin>>maz2[i][j].ch;
maz2[i][j].x = i;
maz2[i][j].y = j;
}
}//存第二幅图
maz1[n-1][m-1].step = -1;
maz2[n-1][m-1].step = -1;//刚开始把两幅图的终点步数都标记成-1
BFS();
if (maz1[n-1][m-1].step == -1 || maz2[n-1][m-1].step == -1)//搜完之后,如果终点步数还是-1的话,说明没有公共路径可达终点
printf("NO\n");
else
{
int ans = maz1[n-1][m-1].step;//记录下刚才搜到的结果
BFS1();
BFS2();
if (ans == maz1[n-1][m-1].step && ans == maz2[n-1][m-1].step)//比较这三个步数是否都相等
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
return 0;
}