AcWing 847. 图中点的层次
原题链接
简单
作者:
自由周某
,
2020-08-21 01:05:40
,
所有人可见
,
阅读 375
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1e5 + 5;
int e[N], ne[N], h[N], id;
int d[N] , q[N]; bool st[N];
void add(int a, int b){
e[id] = b;
ne[id] = h[a];
h[a] = id++;
}
int n;
int bfs(int u){
st[u] = true;
int tt = 0, hh = 0;
d[1] = 0;
while(hh <= tt){
int j = q[hh++];
for(int i = h[j]; i != -1; i = ne[i]) {
int r = e[i];
if(!st[r]){
d[r] = d[j] + 1;
q[++tt] = r;
st[r] = true;
}
}
}
return d[n];
}
int main(){
memset(h, -1, sizeof h);
int n, m;
cin >> n >> m;
for(int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
add(a, b);
}
q[0] = 1;
bfs(1);
if(d[n] == 0) cout<<-1;
else cout<<d[n];
return 0;
}