Playground/자바문제집

[백준] 1697번

미숫가루설탕많이 2023. 5. 17. 00:04

ArrayIndexOutOfBoundsException 에러를 주의해서 코드를 작성해야 한다.

 

public class Main {

    static int N, K;
    static int[] point = new int[100001];

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

        N = Integer.parseInt(st.nextToken());    // 수빈이가 있는 위치
        K = Integer.parseInt(st.nextToken());    // 동생이 있는 위치

        bfs(N);
        System.out.println(point[K] - 1);
    }

    private static void bfs(int node) {
        Queue<Integer> que = new LinkedList<>();
        que.add(node);
        int now = 0;
        point[node] = 1;

        while (!que.isEmpty()) {
            now = que.poll();

            if (now - 1 >= 0 && point[now - 1] == 0) {
                que.add(now - 1);
                point[now - 1] = point[now] + 1;
            }
            if (now + 1 < 100001 && point[now + 1] == 0) {
                que.add(now + 1);
                point[now + 1] = point[now] + 1;
            }
            if (2 * now < 100001 && point[2 * now] == 0) {
                que.add(2 * now);
                point[2 * now] = point[now] + 1;
            }
        }
    }
}

'Playground > 자바문제집' 카테고리의 다른 글

[백준] 11724번  (2) 2023.05.21
[백준] 2667번  (0) 2023.05.18
[백준] 1012번  (0) 2023.05.16
[백준] 2178  (1) 2023.05.16
[백준] 1260번  (0) 2023.05.15