AcWing 847. 图中点的层次
原题链接
简单
作者:
SayYong
,
2024-09-24 09:34:21
,
所有人可见
,
阅读 3
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010;
int h[N], e[N * 2], ne[N * 2], idx;
int dist[N];
bool st[N];
int n, m;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void bfs() {
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
st[1] = true;
queue<int> q;
q.push(1);
while (q.size()) {
int t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (!st[j]) {
dist[j] = dist[t] + 1;
q.push(j);
st[j] = true;
}
}
}
}
int main(void)
{
memset(h, -1, sizeof(h));
cin >> n >> m;
while (m--) {
int a, b;
cin >> a >> b;
add(a, b);
}
bfs();
if (dist[n] == 0x3f3f3f3f)
cout << -1 << endl;
else
cout << dist[n] <<endl;
return 0;
}