forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4.java
62 lines (51 loc) Β· 1.94 KB
/
4.java
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
60
61
62
import java.util.*;
public class Main {
public static final int INF = (int) 1e9; // 무νμ μλ―Ένλ κ°μΌλ‘ 10μ΅μ μ€μ
// λ
Έλμ κ°μ(N), κ°μ μ κ°μ(M), κ±°μ³ κ° λ
Έλ(X), μ΅μ’
λͺ©μ μ§ λ
Έλ(K)
public static int n, m, x, k;
// 2μ°¨μ λ°°μ΄(κ·Έλν νν)λ₯Ό λ§λ€κΈ°
public static int[][] graph = new int[101][101];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
// μ΅λ¨ 거리 ν
μ΄λΈμ λͺ¨λ 무νμΌλ‘ μ΄κΈ°ν
for (int i = 0; i < 101; i++) {
Arrays.fill(graph[i], INF);
}
// μκΈ° μμ μμ μκΈ° μμ μΌλ‘ κ°λ λΉμ©μ 0μΌλ‘ μ΄κΈ°ν
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
if (a == b) graph[a][b] = 0;
}
}
// κ° κ°μ μ λν μ 보λ₯Ό μ
λ ₯ λ°μ, κ·Έ κ°μΌλ‘ μ΄κΈ°ν
for (int i = 0; i < m; i++) {
// Aμ Bκ° μλ‘μκ² κ°λ λΉμ©μ 1μ΄λΌκ³ μ€μ
int a = sc.nextInt();
int b = sc.nextInt();
graph[a][b] = 1;
graph[b][a] = 1;
}
x = sc.nextInt();
k = sc.nextInt();
// μ νμμ λ°λΌ νλ‘μ΄λ μμ
μκ³ λ¦¬μ¦μ μν
for (int k = 1; k <= n; k++) {
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
graph[a][b] = Math.min(graph[a][b], graph[a][k] + graph[k][b]);
}
}
}
// μνλ κ²°κ³Όλ₯Ό μΆλ ₯
int distance = graph[1][k] + graph[k][x];
// λλ¬ν μ μλ κ²½μ°, -1μ μΆλ ₯
if (distance >= INF) {
System.out.println(-1);
}
// λλ¬ν μ μλ€λ©΄, μ΅λ¨ 거리λ₯Ό μΆλ ₯
else {
System.out.println(distance);
}
}
}