AcWing 847. 图中点的层次
原题链接
简单
作者:
szywdwd
,
2021-05-26 20:47:15
,
所有人可见
,
阅读 130
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010;
int n, m;
int h[N], e[N], ne[N], idx;
int d[N];
queue<int> q;
// 添加一条a指向b的边
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
// 1号点到n号点的最短距离,不存在就返回-1
int bfs() {;
q.push(1);
d[1] = 0;
while(q.size()) {
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()
{
cin >> n >> m;
memset(h, -1, sizeof(h));
memset(d, -1, sizeof(d));
for(int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
add(a, b);
}
cout << bfs() << endl;
return 0;
}