728x90
https://www.acmicpc.net/problem/1697
1697번: 숨바꼭질
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일
www.acmicpc.net
// 코드
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
|
import java.util.*;
import java.io.*;
public class Main{
static int N, M;
private static int[] map = new int[100001];
static void getResult() {
Deque<Integer> queue = new ArrayDeque<>();
queue.add(N);
while (!queue.isEmpty()) {
N = queue.pop();
if (N == M) {
break;
}
if (N - 1 >= 0 && map[N - 1] == 0) {
queue.offer(N - 1);
map[N - 1] = map[N] + 1;
}
if (N + 1 <= 100000 && map[N + 1] == 0) {
queue.offer(N + 1);
map[N + 1] = map[N] + 1;
}
if (N * 2 <= 100000 && map[N * 2] == 0) {
queue.offer(N * 2);
map[N * 2] = map[N] + 1;
}
}
}
// main
public static void main(String[] args) throws Exception {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
getResult();
bw.write(String.valueOf(map[M]));
br.close();
bw.flush();
bw.close();
}
}
|
cs |
반응형