Home [BOJ 1697] 숨바꼭질
Post
Cancel

[BOJ 1697] 숨바꼭질

숨바꼭질 (1697번)

https://www.acmicpc.net/problem/1697

풀이방법

  • BFS, DP로 풀 수 있는 문제이다.
  • 거리 배열을 넉넉하게 200,000으로 설정했다.
    • 문제는 100,000까지지만 100,000보다 크게 갔다가 돌아올 수 있으므로
  • +1, -1, *2를 하면서 해당 위치에 값을 입력해주었다. 그렇게되면 현재 위치에서 해당 위치까지 몇 번 움직여야되는지에 대한 답이 나오기 때문이다.
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
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        int K = Integer.parseInt(st.nextToken());
        int[] dist = new int[100_000 * 2];
        Arrays.fill(dist, -1);

        Queue<Integer> queue = new LinkedList<>();
        queue.add(N);
        dist[N] = 0;

        int cur = 0;
        int origin = 0;
        while (dist[K] == -1) {
            origin = queue.poll();

            cur = origin - 1;
            if (cur >= 0 && cur < 100_000*2 && dist[cur] == -1) {
                dist[cur] = dist[origin]+1;
                queue.add(cur);
            }
            cur = origin + 1;
            if (cur >= 0 && cur < 100_000*2 && dist[cur] == -1) {
                dist[cur] = dist[origin]+1;
                queue.add(cur);
            }
            cur = origin * 2;
            if (cur >= 0 && cur < 100_000*2 && dist[cur] == -1) {
                dist[cur] = dist[origin]+1;
                queue.add(cur);
            }
        }

        System.out.println(dist[K]);
    }
}

This post is licensed under CC BY 4.0 by the author.

[BOJ 4179] 불!

[BOJ 1012] 유기농 배추

Comments powered by Disqus.