Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 자바
- java 내림
- time complexity
- 백준 17425
- 0으로 채우기
- sort
- java 올림
- java 반올림
- 백준 16935
- 백준 15661
- 프로그래머스 네트워크 java
- 알고리즘
- 백준 14391
- 백준 18290
- 백준 4375
- 프로그래머스 숫자의 표현 java
- 프로그래머스 연속된 수의 합 java
- mysql
- Math.ceil()
- 네트워크
- Math.floor()
- java
- 코딩테스트
- 프로그래머스 도둑질 java
- Arrays
- 백준 16927
- 프로그래머스 옹알이 java
- Algorithm
- 백준 11723
- Codility
Archives
- Today
- Total
취미처럼
[백준] 13913번 숨바꼭질 4 본문
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