Skip to content

Commit ad2194c

Browse files
committed
230722
1 parent 09353f3 commit ad2194c

File tree

5 files changed

+380
-40
lines changed

5 files changed

+380
-40
lines changed

.idea/workspace.xml

Lines changed: 142 additions & 40 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/graph/BFS/BOJ13549.java

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package graph.BFS;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.util.LinkedList;
7+
import java.util.Queue;
8+
import java.util.StringTokenizer;
9+
10+
public class BOJ13549 {
11+
static int N;
12+
static int K;
13+
static int[] times = new int[100_001];
14+
static int minTime;
15+
16+
public static void main(String[] args) throws IOException {
17+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
18+
StringTokenizer st = new StringTokenizer(br.readLine());
19+
20+
N = Integer.parseInt(st.nextToken());
21+
K = Integer.parseInt(st.nextToken());
22+
23+
if (N >= K) {
24+
System.out.println(N-K);
25+
return;
26+
}
27+
28+
bfs();
29+
System.out.println(minTime-1);
30+
}
31+
32+
static void bfs() {
33+
minTime = 0;
34+
35+
Queue<Integer> que = new LinkedList<>();
36+
que.add(N);
37+
times[N] = 1;
38+
39+
while (!que.isEmpty()) {
40+
int now = que.poll();
41+
42+
if (now == K) {
43+
minTime = times[now];
44+
}
45+
46+
int next = now*2; // 순간이동
47+
if (next <= 100_000) {
48+
if (times[next] == 0 || times[next] > times[now]) {
49+
que.add(next);
50+
times[next] = times[now];
51+
}
52+
}
53+
54+
// 앞 혹은 뒤로 한칸 이동
55+
for (int i = 0; i < 2; i++) {
56+
if (i == 0) next = now-1;
57+
else next = now+1;
58+
59+
if (next < 0 || next > 100_000) continue;
60+
61+
if (times[next] == 0 || times[next] > times[now] + 1) {
62+
que.add(next);
63+
times[next] = times[now] + 1;
64+
}
65+
}
66+
67+
}
68+
}
69+
70+
}

0 commit comments

Comments
 (0)