b13913. μκ°μ΄λ 4
π μλ°(Java)λ‘ νΈλ μ¨λ°κΌμ§ 4 - λ°±μ€ 13913π§βοΈβ‘οΈπ§βοΈ
μ΅μ μκ° + μ΄λ κ²½λ‘κΉμ§ μΆλ ₯νλ BFS λ¬Έμ !
π λ¬Έμ κ°μ
λ°±μ€ 13913λ² - μ¨λ°κΌμ§ 4λ
μ μ N(μλΉμ΄ μμΉ)μμ K(λμ μμΉ)κΉμ§
λ€μ μΈ κ°μ§ μ°μ°μΌλ‘ μ΄λν΄ μ΅μ μκ°μ ꡬνλ λ¬Έμ μ λλ€.
- X - 1
- X + 1
- X * 2
λΏλ§ μλλΌ,
β μ΅λ¨ μκ°κ³Ό ν¨κ»
β κ·Έλμ μ΄λ κ²½λ‘λ₯Ό μ νν μΆλ ₯ν΄μΌ ν©λλ€!
π‘ μμ μ λ ₯
5 17
π‘ μμ μΆλ ₯
4
5 10 9 18 17
π μκ³ λ¦¬μ¦ μ κ·Ό λ°©μ
μ΄ λ¬Έμ λ μ νμ μΈ μ΅λ¨ 거리 νμ → BFS λ¬Έμ μ λλ€.
νμ§λ§ κ²½λ‘ μΆμ κΉμ§ ν΄μΌ νλ―λ‘,
β μ΄λ μ΄μ μμΉλ₯Ό κΈ°λ‘νλ prev[] λ°°μ΄μ νμ©ν΄μΌ ν©λλ€.
πΉ Java μ½λ μ€λͺ
π Node ν΄λμ€
static class Node {
int position;
int time;
...
}
β νμ¬ μμΉμ κ±Έλ¦° μκ°μ ν¨κ» μ μ₯νλ ν΄λμ€
π BFS λ‘μ§
static int bfs() {
Queue<Node> queue = new ArrayDeque<>();
queue.offer(new Node(start, 0));
visited[start] = true;
while (!queue.isEmpty()) {
Node current = queue.poll();
if (current.position == end) {
return current.time;
}
for (int next : new int[]{current.position - 1, current.position + 1, current.position * 2}) {
if (next >= 0 && next < MAX && !visited[next]) {
visited[next] = true;
prev[next] = current.position;
queue.offer(new Node(next, current.time + 1));
}
}
}
return -1;
}
β visited[]λ‘ μ€λ³΅ λ°©λ¬Έ λ°©μ§
β prev[next] = current.positionλ‘ κ²½λ‘ μ μ₯
β λμ°©νλ©΄ current.timeμ λ°ν
π κ²½λ‘ μΆλ ₯ λ‘μ§
static void printPath() {
Deque<Integer> path = new ArrayDeque<>();
for (int at = end; at != -1; at = prev[at]) {
path.push(at);
}
StringBuilder sb = new StringBuilder();
while (!path.isEmpty()) {
sb.append(path.pop()).append(" ");
}
System.out.println(sb.toString().trim());
}
β prev[]λ₯Ό κ±°μ¬λ¬ μ¬λΌκ°λ©° stackμ μ μ₯
β stackμ μ¬μ©ν΄ μμλλ‘ μΆλ ₯
π μ 리
β ν΅μ¬ ν¬μΈνΈ
- BFSλ μ΅λ¨ 거리 νμμ μ ν©
- κ²½λ‘ λ³΅μμ prev[] λ°°μ΄μ ν΅ν΄
- O(N) μκ° μμ μ λ΅ κ²½λ‘ μΆμ κ°λ₯