Skip to content

Commit 28a2380

Browse files
authored
Merge pull request #998 from AlgorithmWithGod/JHLEE325
[20250929] BOJ / G5 / 1로 만들기 2 / 이준희
2 parents 030aef1 + e6c9b21 commit 28a2380

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
static class Node {
8+
int num;
9+
int depth;
10+
Node prev;
11+
Node(int num, int depth, Node prev) {
12+
this.num = num;
13+
this.depth = depth;
14+
this.prev = prev;
15+
}
16+
}
17+
18+
public static void main(String[] args) throws IOException {
19+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
20+
StringTokenizer st;
21+
22+
int n = Integer.parseInt(br.readLine());
23+
24+
boolean[] visited = new boolean[n + 1];
25+
Queue<Node> q = new LinkedList<>();
26+
q.offer(new Node(n, 0, null));
27+
visited[n] = true;
28+
29+
Node end = null;
30+
31+
while (!q.isEmpty()) {
32+
Node cur = q.poll();
33+
34+
if (cur.num == 1) {
35+
end = cur;
36+
break;
37+
}
38+
39+
if (cur.num - 1 >= 1 && !visited[cur.num - 1]) {
40+
visited[cur.num - 1] = true;
41+
q.offer(new Node(cur.num - 1, cur.depth + 1, cur));
42+
}
43+
44+
if (cur.num % 2 == 0 && !visited[cur.num / 2]) {
45+
visited[cur.num / 2] = true;
46+
q.offer(new Node(cur.num / 2, cur.depth + 1, cur));
47+
}
48+
49+
if (cur.num % 3 == 0 && !visited[cur.num / 3]) {
50+
visited[cur.num / 3] = true;
51+
q.offer(new Node(cur.num / 3, cur.depth + 1, cur));
52+
}
53+
}
54+
55+
StringBuilder sb = new StringBuilder();
56+
sb.append(end.depth).append("\n");
57+
58+
List<Integer> path = new ArrayList<>();
59+
while (end != null) {
60+
path.add(end.num);
61+
end = end.prev;
62+
}
63+
64+
for (int i = path.size()-1; i >= 0; i--) {
65+
sb.append(path.get(i) + " ");
66+
}
67+
68+
System.out.println(sb.toString());
69+
}
70+
}
71+
```

0 commit comments

Comments
 (0)