#include<cstdio>
#include<iostream>
using namespace std;
struct note{
int x;//城市博客编号
int s;//转机次数
};
int main(){
struct note que[2501];
int e[51][51]={0},book[51]={0};
int head,tail;
int i,j,n,m,a,b,cur,start,end,flag=0;
cin>>n>>m>>start>>end;
//初始化二维矩阵
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]=999999;
//读入整体数据
for(int i=1;i<=m;i++){
cin>>a>>b;
e[a][b]=1;
e[b][a]=1;
}
//队列初始化
head=1; tail=1;
que[tail].x=start;
que[tail].s=0;
tail++;
book[start]=1;//标记start号城市已在队列中
//当队列不为空时循环
while(head<tail){
cur=que[head].x;
//从城市cur到城市j是否有航班且是否在队列中
for(int j=1;j<=n;j++){
if(e[cur][j]!=999999&&book[j]==0){
que[tail].x=j;
//cout<<"que[tail].x "<<que[tail].x<<endl;
que[tail].s=que[head].s+1;
//cout<<"que[tail].s "<<que[tail].s<<endl;
tail++;
//cout<<"tail "<<tail<<endl;
book[j]=1;
}
if(que[tail-1].x==end){
flag=1;
break;
}
}
if(flag==1)
break;
head++;
//cout<<"head "<<head<<endl;
}
cout<<que[tail-1].s;
}
最少转机-图的广度优先遍历
最新推荐文章于 2022-04-22 16:52:00 发布