
๐ ์๋ฐ(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) ์๊ฐ ์์ ์ ๋ต ๊ฒฝ๋ก ์ถ์ ๊ฐ๋ฅ
'Algorithm & Data Structures > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
b2263. ํธ๋ฆฌ์ ์ํ (0) | 2025.04.28 |
---|---|
b11780. ํ๋ก์ด๋ 2 (0) | 2025.04.25 |
b2618. ๊ฒฝ์ฐฐ์ฐจ (0) | 2025.04.18 |
b14003. ๊ฐ์ฅ ๊ธด ์ฆ๊ฐํ๋ ๋ถ๋ถ์์ด 5 (0) | 2025.04.16 |
b14002. ๊ฐ์ฅ ๊ธด ์ฆ๊ฐํ๋ ๋ถ๋ถ์์ด 4 (0) | 2025.04.15 |