图中点的层次
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int h[N],e[N],ne[N],idx,d[N],n,m;
void add(int a,int b){
e[idx] = b,ne[idx] = h[a],h[a] = idx ++;
}
int bfs(){
memset(d,-1,sizeof d);
d[1] = 0;
queue<int> q;
q.push(1);
while(!q.empty()){
int t = q.front();
q.pop();
for(int i = h[t]; ~i; i = ne[i]){
int j = e[i];
if(d[j] == -1){
d[j] = d[t] + 1;
q.push(j);
}
}
}
return d[n];
}
int main(){
memset(h, -1, sizeof h);
cin >> n >> m;
while(m --){
int a,b;
cin >> a >> b;
add(a,b);
}
cout << bfs() << endl;
return 0;
}