/
BAEKJOON 14496
59 lines (52 loc) · 1.52 KB
/
BAEKJOON 14496
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
54
55
56
57
58
59
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
static int a,b,N,M, ans = Integer.MAX_VALUE;
static boolean[] visit;
static ArrayList<Integer>[] list;
static PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[1] - b[1]);
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
visit = new boolean[N+1];
list = new ArrayList[N+1];
for (int i = 0; i < N+1; i++) {
list[i] = new ArrayList<>();
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int s = Integer.parseInt(st.nextToken());
int e = Integer.parseInt(st.nextToken());
list[s].add(e);
list[e].add(s);
}
pq.add(new int[] {a,0});
visit[a] = true;
while(!pq.isEmpty()) {
int[] n = pq.poll();
if(n[0] == b) {
ans = Math.min(ans, n[1]);
continue;
}
for (int i = 0; i < list[n[0]].size(); i++) {
int next = list[n[0]].get(i);
if(!visit[next]) {
pq.add(new int[] {next,n[1]+1});
visit[next] = true;
}
}
}
if (ans == Integer.MAX_VALUE)
System.out.println(-1);
else
System.out.println(ans);
}
}