BFS-最短路径
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
int h[N], ne[N], e[N], idx;
int n, m;
bool st[N];
int dis[N];
queue<int> q;
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++ ;
}
int main() {
memset(h, -1, sizeof h);
memset(dis, 0x3f3f3f, sizeof dis);
cin >> n >> m;
for (int i = 0; i < m; i ++ ) {
int a, b;
cin >> a >> b;
add(a, b);
}
dis[1] = 0;
st[1] = true;
q.push(1);
while(!q.empty()) {
int t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (st[j]) continue;
st[j] = true;
dis[j] = dis[t] + 1;
q.push(j);
}
}
if(dis[n] != 0x3f3f3f3f) cout << dis[n] << endl;
else cout << -1 << endl;
return 0;
}