bfs-求图中点的层次
重点
1. 点的层次和边权没有关系,从源点出发每次向外扩展一层,第一次遇到某个点的时候,这个路径就是点的层次
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010, M = N * 2;
int h[N], ne[M], e[M], cnt;
bool st[N];
int dist[N];
int n, m;
void add(int a, int b) {
e[cnt] = b, ne[cnt] = h[a], h[a] = cnt++;
}
void bfs(int u) {
queue<int> q;
memset(dist, 0x3f, sizeof(dist));
q.push(u);
dist[u] = 0;
st[u] = true;
while (q.size()) {
auto t = q.front();
q.pop();
int dis = dist[t];
for (int i = h[t]; ~i; i = ne[i]) {
int j = e[i];
if (st[j]) continue;
dist[j] = dis + 1;
st[j] = true;
q.push(j);
}
}
}
int main() {
cin >> n >> m;
memset(h, -1, sizeof(h));
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
add(a, b);
}
bfs(1);
if (dist[n] == 0x3f3f3f3f) cout << -1 << endl;
else cout << dist[n] << endl;
return 0;
}