首页 > 其他 > 详细

(BFS遍历 邻接矩阵)最少转机

时间:2020-03-27 17:02:19      阅读:104      评论:0      收藏:0      [点我收藏+]

题意:小哼和小哈一起坐飞机旅游,他们现在位于start号城市,目标是end号城市,可是start号城市没有到end号城市直航,

     不过他们收集了很多航班信息,现在他们要找出转机次数最少的方案。

输入样例:

5 7 1 5

1 2

1 3

2 3

2 4

3 4

3 5

4 5

第一行的5表示有5个城市(编号为1~5),7表示有7条航线,1表示起始城市,5表示目标城市,接下来的每行“a b”,表示a,b之间有航线,也就是a,b之间可以相互到达。

输出样例:

2

#include <cstdio>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <math.h>
#include <queue>
using namespace std;
const int inf=0x7fffffff;
const long long mod=1e9+7;
const double PI=acos(-1);

int n,m,start,end;
int ans=9999999;
bool vis[105];
int e[105][105];

struct node{
    int s;
    int d;
    node(int ss,int dd){
        s=ss;
        d=dd;
    }
};

void init(){                           //初始化邻接矩阵 
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(i==j) e[i][j]=0;
            else e[i][j]=99999999;
        }
    }
} 

int bfs(int pos){
    queue<node> q;
    vis[pos]=1;                                  //设置起点被遍历 
    q.push(node(pos,0));                         //放入队列起点 
    while(!q.empty()){
        node now=q.front();                      //now为此时遍历的点 
        q.pop();
        for(int i=1;i<=n;i++){                   //找可以和 now 连通的点  
            if(e[now.s][i]!=99999999&&!vis[i]){  //和 now 连通则标记 并加入队列 
                q.push(node(i,now.d+1));
                vis[i]=1;
            }
            if(now.s==end){                      //找到终点直接退出 
                return q.back().d;
            }
        }
    }
    return -1;
}
int main()
{
    int x,y;
    cin>>n>>m>>start>>end;
    init();
    for(int i=0;i<m;i++){                      //输入边 
        cin>>x>>y;
        e[x][y]=1;
        e[y][x]=1;
    }
    cout<<bfs(start);
    return 0;
}

 

(BFS遍历 邻接矩阵)最少转机

原文:https://www.cnblogs.com/xusi/p/12582295.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!