题目描述
小哼和小哈一同坐飞机去旅游,他们现在位于1号城市,目标是5号城市,可是1号城市并没有到5号城市的直航。不过小哼已经收集了很多航班的信息,现在小哼希望找到一种乘坐方式,使得转机的次数最少,如何解决呢?
输入
第一行的有两个整数n m s e,n表示有n个城市(城市编号为1~n),m表示有m条航线,s表示起点城市,e表示目标城市。
接下来m行每行是一条类似“a b”这样的数据表示城市a和城市b之间有航线,也就是说城市a和城市b之间可以相互到达
输出
s号城市到e号目标城市,需要飞行几次?
1<=n<=1000, 1<=m<=300000
示例
输入:
5 7 1 5
1 2
1 3
2 3
2 4
3 4
3 5
4 5
输出:
2
代码
#include<bits/stdc++.h>
using namespace std;
int a[100][100],book[100];
int n,m,endx;
struct node
{
int x;
int step;
node (int xx,int step1):x(xx),step(step1){}
};
void bfs(int cur,int dis)
{
queue<node>q;
q.push(node(cur,dis));
book[cur]=1;
while(!q.empty())
{
node e=q.front();
if(e.x==endx)
{
cout<<e.step<<endl;
}
for(int i=1;i<=n;i++)
{
if(!book[i]&&a[e.x][i]!=99999)
{
book[i]=1;
q.push(node(i,e.step+a[e.x][i]));
}
}
q.pop();
}
}
int main()
{
int b,c,startx;
cin>>n>>m>>startx>>endx;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(i==j)
a[i][j]=0;
else
a[i][j]=99999;
for(int i=1;i<=m;i++)
{
cin>>b>>c;
a[b][c]=1;
a[c][b]=1;
}
book[startx]=1;
bfs(startx,0);
return 0;
}