#include<iostream>
#include<cstring>
using namespace std;
const int N=100010;
int e[N],ne[N],h[N],d[N],q[N],idx;
int n,m;
void add(int a,int b){
e[idx]=b;
ne[idx]=h[a];
h[a]=idx++;
}
int bfs(){
int hh=0,tt=-1;
q[++tt] = 1;
memset(d,-1,sizeof d);
d[1]=0;
while(hh<=tt){
int t=q[hh++];
for(int i=h[t];i!=-1;i=ne[i]){
int j=e[i];
if(d[j]==-1){
d[j]=d[t]+1;
q[++tt]=j;
}
}
}
return d[n];
}
int main(){
scanf("%d%d",&n,&m);
memset(h,-1,sizeof h);
while(m--){
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
}
printf("%d",bfs());
}
图中点的层次(BFS) C++实现847
最新推荐文章于 2025-10-26 21:35:32 发布
本文介绍了使用C++编程语言实现图的邻接表表示法,并通过add函数添加边,使用深度优先搜索(bfs)算法求解从给定起点到其他顶点的最短路径,展示了基础图论在实际编程中的应用。
61

被折叠的 条评论
为什么被折叠?



