POJ 3170--双重BFS

题意:

给一个 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值