AcWing 847. 图中点的层次
原题链接
简单
作者:
slim_
,
2024-04-23 20:19:36
,
所有人可见
,
阅读 2
vector存图+queue搜索
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int N = 100010;
int n, m;
vector<int> h[N];
int d[N];
int bfs() {
memset(d, -1, sizeof d);
queue<int> q;
d[1] = 0;
q.push(1);
while (!q.empty()) {
int t = q.front();
q.pop();
for (int j : h[t]) {
if (d[j] == -1) {
d[j] = d[t] + 1;
q.push(j);
}
}
}
return d[n];
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", &a, &b);
h[a].push_back(b);
}
cout << bfs() << endl;
return 0;
}