您的位置:首页 > 其它

POJ 3170--双重BFS

2016-07-28 20:58 295 查看
题意:

给一个 n 列 m行的矩阵,矩阵元素只有0,1,2,3,4,0表示可通过,1表示不可通过,矩阵中只有一个2和3,其他数字不限制,的问从2

开始到所有的4在折回到3的最短路是多少。

输入:

8 4
4 1 0 0 0 0 1 0
0 0 0 1 0 1 0 0
0 2 1 1 3 0 4 0
0 0 0 4 1 1 1 0

输出:

11

分析:

两个BFS,先从2到4,再从4到3.

代码:

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define inf 0x3f3f3f3f
using namespace std;

const int maxn=1005;
int a[maxn][maxn],vis[maxn][maxn],dist1[maxn][maxn],dist2[maxn][maxn];
int n,m,ans;
int dr[]= {0,0,1,-1};
int dc[]= {1,-1,0,0};
struct node
{
int x,y;
} s1,s2,t;

void bfs()
{
queue<node> q;
dist1[s1.x][s1.y]=0;
q.push(s1);
while(!q.empty())
{
node p=q.front();
q.pop();
int r=p.x;
int c=p.y;
for(int i=0; i<4; i++)
{
int rr=r+dr[i];
int cc=c+dc[i];
if(rr>=1&&rr<=m&&cc>=1&&cc<=n&&a[rr][cc]!=1&&dist1[rr][cc]==inf)
{
vis[rr][cc]=1;
t.x=rr;
t.y=cc;
dist1[rr][cc]=dist1[r][c]+1;
q.push(t);
}
}
}
while(!q.empty())
q.pop();
dist2[s2.x][s2.y]=0;
q.push(s2);
while(!q.empty())
{
node p=q.front();
q.pop();
int r=p.x;
int c=p.y;
for(int i=0; i<4; i++)
{
int rr=r+dr[i];
int cc=c+dc[i];
if(rr>=1&&rr<=m&&cc>=1&&cc<=n&&a[rr][cc]!=1&&dist2[rr][cc]==inf)
{
vis[rr][cc]=1;
t.x=rr;
t.y=cc;
dist2[rr][cc]=dist2[r][c]+1;
q.push(t);
}
}
}
for(int i=1; i<=m; i++)
{
for(int j=1; j<=n; j++)
{
if(a[i][j]==4&&dist1[i][j]!=inf&&dist2[i][j]!=inf)
ans=min(ans,dist1[i][j]+dist2[i][j]);
}
}

}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1; i<=m; i++)
{
for(int j=1; j<=n; j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]==2)
{
s1.x=i;
s1.y=j;
}
if(a[i][j]==3)
{
s2.x=i;
s2.y=j;
}
}
}
memset(dist2,inf,sizeof(dist2));
memset(dist1,inf,sizeof(dist1));
ans=inf;
bfs();
printf("%d\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: