AcWing 847. [Java] 图中点的层次
原题链接
简单
作者:
Aranne
,
2020-07-17 13:12:38
,
所有人可见
,
阅读 351
import java.util.*;
class Main {
Scanner sc = new Scanner(System.in);
int n, m;
int N = 100005;
List<Integer>[] g = new List[N];
int[] dist = new int[N];
void run() {
n = sc.nextInt(); m = sc.nextInt();
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt() - 1, b = sc.nextInt() - 1;
if (a == b) continue;
g[a].add(b);
}
Queue<Integer> queue = new LinkedList<>();
Arrays.fill(dist, -1);
dist[0] = 0;
queue.add(0);
while (!queue.isEmpty()) {
int u = queue.poll();
for (int v : g[u]) {
if (dist[v] != -1) continue;
dist[v] = dist[u] + 1;
if (v == n - 1) {
System.out.println(dist[v]);
return;
}
queue.add(v);
}
}
System.out.println(-1);
}
public static void main(String[] args) {
Main m = new Main();
m.run();
}
}