AcWing 847. 图中点的层次
原题链接
简单
作者:
piaofan
,
2021-02-22 15:52:08
,
所有人可见
,
阅读 233
#include<bits/stdc++.h>
using namespace std;
const int N = 100005;
int n, e[N], ne[N], h[N], idx = 1;
int d[N];
bool vis[N];
queue<int> q;
void add (int a, int b) {
e[idx] = b; ne[idx] = h[a]; h[a] = idx++;
}
int bfs () {
memset(d, -1, sizeof(d));
q.push(1);
d[1] = 0;
while (!q.empty()) {
int t = q.front(); q.pop();
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (d[j] == -1) {
d[j] = d[t] + 1;
q.push(j);
}
}
}
return d[n];
}
int main (void) {
int m;
cin >> n >> m;
memset(h, -1, sizeof(h));
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
add(a, b);
}
cout << bfs();
return 0;
}