Skip to content

Commit 1c27cd1

Browse files
committed
[Week08] BOJ 13549: 숨바꼭질 3
1 parent 70ec702 commit 1c27cd1

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package it_company_work_book.gold;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.util.Arrays;
7+
import java.util.PriorityQueue;
8+
9+
// 숨바꼭질 3
10+
// dp, bfs
11+
/**
12+
* 메모리 초과 이슈로 시간이 오래 걸렸다.
13+
* 현재 위치 N 에서 K까지 가는 최소의 경우를 구하면 된다.
14+
* N과 K 의 위치가 동적이기 때문에 dp 배열을 선언할 때, 문제에서 모든 값을 처리 가능한 배열 사이즈로 초기화
15+
* 현재 위치에서 x2 를 하는 방식이 최소 이동 방식이기 때문에 먼저 진행한다. 배열 범위 내에서 x2 가 가능하다면 dp 를 업데이트하고 큐에 넣는다.
16+
* -1 과 1 은 cost가 1 증가하므로 이를 고려하여 dp 를 업데이트하고 q에 넣는다.
17+
* q에서 꺼낸 Point가 K와 같다면 현재 cost를 출력하고 종료한다.
18+
*/
19+
public class BOJ_13549 {
20+
21+
static class Point {
22+
23+
int idx;
24+
int cost;
25+
26+
public Point(int idx, int cost) {
27+
this.idx = idx;
28+
this.cost = cost;
29+
}
30+
}
31+
32+
public static void main(String[] args) throws IOException {
33+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
34+
35+
String[] s = br.readLine().split(" ");
36+
37+
int N = Integer.parseInt(s[0]);
38+
int K = Integer.parseInt(s[1]);
39+
40+
if(N == K){
41+
System.out.println(0);
42+
return;
43+
}
44+
45+
int []dp = new int[100001];
46+
Arrays.fill(dp, Integer.MAX_VALUE);
47+
PriorityQueue<Point> pq = new PriorityQueue<>((p1, p2) -> {
48+
return p1.cost - p2.cost;
49+
});
50+
51+
pq.offer(new Point(N, 0));
52+
dp[N] = 0;
53+
54+
while (!pq.isEmpty()) {
55+
Point point = pq.poll();
56+
int now = point.idx;
57+
int cost = point.cost;
58+
if(now == K){
59+
System.out.println(cost);
60+
return;
61+
}
62+
63+
if (now * 2 < 100001 && cost < dp[now*2]) {
64+
dp[now*2] = dp[now];
65+
pq.offer(new Point(now * 2, dp[now*2]));
66+
}
67+
68+
if (now - 1 >= 0 && cost + 1< dp[now-1]) {
69+
dp[now-1] = dp[now]+1;
70+
pq.offer(new Point(now - 1, dp[now-1]));
71+
}
72+
73+
if (now + 1 < 100001 && cost + 1 < dp[now+1]) {
74+
dp[now+1] = dp[now]+1;
75+
pq.offer(new Point(now + 1, dp[now+1]));
76+
}
77+
}
78+
}
79+
}

0 commit comments

Comments
 (0)