AcWing 847. 图中点的层次
原题链接
简单
作者:
sca
,
2023-12-13 11:15:38
,
所有人可见
,
阅读 33
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1e5 + 10;
const int M = 2 * N;
int n, m;
int e[N], ne[M], idx, d[N], st[N], h[N];
queue<int> q;
void add (int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
int dfs()
{
memset(d, -1, sizeof d);
d[1] = 0;
st[1] = 1; //走过
q.push(1);
while (!q.empty())
{
int t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j])
{
d[j] = d[t] + 1;
q.push(j);
st[j] = 1;
}
}
}
return d[n];
}
int main ()
{
memset(h, -1, sizeof h);
cin >> n >> m;
while (m--)
{
int a, b;
cin >> a >> b;
add(a, b);
}
cout << dfs() << endl;
}