blob: d56c1345c3c41269977debe0433cb10104277efe (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BFS {
private static int distance(ArrayList<Integer>[] adj, int s, int t) {
int[] dist = new int[adj.length];
Arrays.fill(dist, -1);
dist[s] = 0;
bfs(adj, s, dist);
return dist[t];
}
private static void bfs(ArrayList<Integer>[] adj, int s, int[] dist) {
Queue<Integer> vertexQ = new LinkedList<>();
vertexQ.add(s);
while (!vertexQ.isEmpty()) {
int u = vertexQ.remove();
for (int i : adj[u]) {
if (dist[i] == -1) {
vertexQ.add(i);
dist[i] = dist[u] + 1;
}
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
ArrayList<Integer>[] adj = (ArrayList<Integer>[]) new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++) {
int x, y;
x = scanner.nextInt();
y = scanner.nextInt();
adj[x - 1].add(y - 1);
adj[y - 1].add(x - 1);
}
int x = scanner.nextInt() - 1;
int y = scanner.nextInt() - 1;
System.out.println(distance(adj, x, y));
}
}
|