분류
너비 우선 탐색, 그래프 이론, 그래프 탐색
문제 설명
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 1초 후에 2*X의 위치로 이동하게 된다.
수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오.
입력
첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. N과 K는 정수이다.
출력
첫째 줄에 수빈이가 동생을 찾는 가장 빠른 시간을 출력한다.
둘째 줄에 어떻게 이동해야 하는지 공백으로 구분해 출력한다.
풀이 (BFS 너비 우선 탐색)
시간 복잡도 O(n) 공간 복잡도 O(n)
아이디어: 숨바꼭질과 동일 https://suhanlim.tistory.com/279
역추적은 따로 map 만큼의 history 배열을 만들어서 해당 칸에 방문하기전 이전 칸을 기록하는 방식을 이용하여 진행한다.
map[pos+1] = time+1, 과 같이 갱신 작업을 할 때 histroy[pos+1] = pos 와 같은 식으로 이전에 방문한 기록을 저장한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
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());
Queue<int[]> queue = new LinkedList<>();
int[] map = new int[100001];
int[] history = new int[100001];
Arrays.fill(map,-1);
ArrayList<Integer> ans = new ArrayList<>();
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
map[n] = 0;
queue.add(new int[]{n, 0});
while(!queue.isEmpty()){
int[] current = queue.poll();
int pos = current[0];
int time = current[1];
// 목표를 잡은 경우
if (pos == k) {
System.out.println(time);
break;
}
// 한 칸 뒤로
if (pos - 1 >= 0 && map[pos - 1] == -1) {
map[pos - 1] = time + 1;
history[pos-1] = pos;
queue.add(new int[]{pos - 1, time + 1});
}
// 한 칸 앞으로
if (pos + 1 <= 100000 && map[pos + 1] == -1) {
map[pos + 1] = time + 1;
history[pos+1] = pos;
queue.add(new int[]{pos + 1, time + 1});
}
// 텔레포트
if (pos * 2 <= 100000 && map[pos * 2] == -1) {
map[pos * 2] = time + 1;
history[pos*2] = pos;
queue.add(new int[]{pos * 2, time + 1});
}
}
// 역추적 시작
int search = k;
Stack<Integer> stack = new Stack<>();
while(search!=n){
stack.push(search);
search = history[search];
}
stack.add(n);
while (!stack.isEmpty()) {
System.out.print(stack.pop()+" ");
}
}
}
'PS > Gold' 카테고리의 다른 글
| [Gold V] 숨바꼭질 3 - 13549 (Java) (0) | 2023.08.16 |
|---|---|
| [Gold V] 토마토 - 7569 (Java) (0) | 2023.08.15 |
| [Gold V] 토마토 - 7576 (Java) (0) | 2023.08.02 |
| [Gold III] Happy Cow - 13002 (Java) (0) | 2023.07.29 |
| [Gold III] 수확 - 1823 (Java) (0) | 2023.07.29 |