H: 地图
题意:
两个大小相同的图,图上都有若干障碍,问是否存在一条一样的最短路径从左上角到右下角。
题解:
一道bfs的题,跑三次bfs,两个图分别跑一次,然后将两个图合起来,将它们的障碍点合起来,然后再跑一遍bfs,若三次均可以到达终点并且路径长度相同,即存在一条相同的最短路径。
#include<bits/stdc++.h>
using namespace std;
char a[505][505],b[505][505],c[505][505];
int vis[505][505];
int n,m;
struct node
{
int x,y;
int cnt;
};
bool check(int x,int y,int num)
{
if(num==1)
{
if(x<0 || y<0 ||x>n-1 || y>m-1 || a[x][y]=='#' || vis[x][y])
return 0;
}
else if(num==2)
{
if(x<0 || y<0 ||x>n-1 || y>m-1 || b[x][y]=='#' || vis[x][y])
return 0;
}
else if(num==3)
{
if(x<0 || y<0 ||x>n-1 || y>m-1 || c[x][y]=='#' || vis[x][y])
return 0;
}
return 1;
}
int bfs(int num)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
vis[i][j]=0;
}
queue<node> q;
node now,next;
now.x=0,now.y=0,now.cnt=1;
vis[now.x][now.y]=1;
q.push(now);
while(!q.empty())
{
now=q.front();
q.pop();
if(now.x==n-1 && now.y==m-1)
return now.cnt;
if(check(now.x+1,now.y,num))
{
next=now;
next.x+=1;
next.cnt++;
vis[next.x][next.y]=1;
q.push(next);
}
if(check(now.x,now.y+1,num))
{
next=now;
next.y+=1;
next.cnt++;
vis[next.x][next.y]=1;
q.push(next);
}
if(check(now.x,now.y-1,num))
{
next=now;
next.y-=1;
next.cnt++;
vis[next.x][next.y]=1;
q.push(next);
}
if(check(now.x-1,now.y,num))
{
next=now;
next.x-=1;
next.cnt++;
vis[next.x][next.y]=1;
q.push(next);
}
}
return 0;
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
scanf("%s",a+i);
for(int i=0;i<n;i++)
scanf("%s",b+i);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
c[i][j]=a[i][j];
if(b[i][j]=='#')
c[i][j]='#';
}
}
if(bfs(1)==bfs(2) && bfs(1)==bfs(3) && bfs(3))
printf("YES");
else
printf("NO");
return 0;
}