홈 BOJ. Hide and Seek (1697)
글
취소

BOJ. Hide and Seek (1697)

풀이

0부터 100000까지의 정수를 각각 하나의 상태로 봅니다. 상태 x에서는 결과가 허용 범위 안에 있을 때 x - 1, x + 1, 2 * x로 한 번에 이동할 수 있습니다. 모든 간선의 비용이 1이므로 너비 우선 탐색(BFS)은 시작점으로부터의 거리가 작은 상태부터 방문합니다. 따라서 목표를 처음 발견했을 때의 이동 횟수가 최단 거리입니다.

거리 배열은 방문 여부도 표시합니다. -1은 아직 방문하지 않은 상태를 뜻합니다. 각 상태는 큐에 최대 한 번만 들어가므로 시간 복잡도는 O(100000), 공간 복잡도는 O(100000)입니다.

문제 링크

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {
    private static final int MAX = 100000;

    public static void main(String[] args) throws IOException {
        StringTokenizer input = new StringTokenizer(
                new BufferedReader(new InputStreamReader(System.in)).readLine());
        int start = Integer.parseInt(input.nextToken());
        int target = Integer.parseInt(input.nextToken());
        if (start == target) {
            System.out.println(0);
            return;
        }

        int[] distance = new int[MAX + 1];
        Arrays.fill(distance, -1);
        int[] queue = new int[MAX + 1];
        int head = 0;
        int tail = 0;

        distance[start] = 0;
        queue[tail++] = start;

        while (head < tail) {
            int current = queue[head++];
            int nextDistance = distance[current] + 1;

            if (current - 1 >= 0 && distance[current - 1] == -1) {
                if (current - 1 == target) {
                    System.out.println(nextDistance);
                    return;
                }
                distance[current - 1] = nextDistance;
                queue[tail++] = current - 1;
            }
            if (current + 1 <= MAX && distance[current + 1] == -1) {
                if (current + 1 == target) {
                    System.out.println(nextDistance);
                    return;
                }
                distance[current + 1] = nextDistance;
                queue[tail++] = current + 1;
            }
            if (current * 2 <= MAX && distance[current * 2] == -1) {
                if (current * 2 == target) {
                    System.out.println(nextDistance);
                    return;
                }
                distance[current * 2] = nextDistance;
                queue[tail++] = current * 2;
            }
        }
    }
}
이 글은 저자가 CC BY 4.0 라이선스로 배포합니다.