취미처럼

[백준] 13913번 숨바꼭질 4 본문

Algorithm/백준

[백준] 13913번 숨바꼭질 4

sirius 2021. 3. 11. 10:11
https://www.acmicpc.net/problem/13913
 

13913번: 숨바꼭질 4

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

www.acmicpc.net

parent 배열에 직전 번호를 기록하여 이동 경로 저장

 

import java.util.*;
import java.io.*;

public class Main {

    static int N;
    static int K;
    static boolean[] visit = new boolean[100001];
    static int[] arr = new int[100001];
    static int[] parent = new int[100001];
    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws Exception {

        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        K = sc.nextInt();

        Arrays.fill(parent, -1);
        if (N == K) {
        	System.out.print(0);
        } else {
       		bfs();
        }

        sb.append(arr[K]).append("\n");

        Stack<Integer> stack = new Stack<>();
        stack.push(K);
        while(parent[K] != -1) {
        	stack.push(parent[K]);
        	K = parent[K];
        }
        while(!stack.isEmpty()) {
        	sb.append(stack.pop() + " ");
        }
        System.out.println(sb);

    }

    public static void bfs() {
        Queue<Integer> q = new LinkedList<>();
        q.offer(N);
        visit[N] = true;
        while (!q.isEmpty()) {
            int num = q.poll();

            for (int i = 0; i < 3; i++) {
                int next = 0;
                if (i == 0) {
                	next = num - 1;
                } else if (i == 1) {
                	next = num + 1;
                } else {
                	next = num * 2;
                }

                if (next >= 0 && next < arr.length && !visit[next]) {
                    q.offer(next);
                    arr[next] = arr[num] + 1;
                    parent[next] = num;
                    visit[next] = true;
                }
            }

        }
    }

}

 

 

'Algorithm > 백준' 카테고리의 다른 글

[백준] 13549번 숨바꼭질3  (0) 2021.03.11
[백준] 14226번 이모티콘  (0) 2021.03.11
[백준] 1697번 숨바꼭질  (0) 2021.03.11
[백준] 7562번 나이트의 이동  (0) 2021.03.11
[백준] 7576번 토마토  (0) 2021.03.11
Comments