๋ฌธ์
https://www.acmicpc.net/problem/31248
ํ์ด
1. (N - 2)๊ฐ๋ฅผ D๊ฐ ์๋ ๊ธฐ๋ฅ์ผ๋ก ์ฎ๊ธฐ๊ธฐ
2. ๋ ๋ฒ์งธ๋ก ํฐ ์ํ์ D๊ฐ ์๋ ๋ค๋ฅธ ๋น์ด์๋ ๊ธฐ๋ฅ์ผ๋ก ์ฎ๊ธฐ๊ธฐ
3. ๊ฐ์ฅ ํฐ ์ํ์ D๋ก ์ฎ๊ธฐ๊ธฐ
4. ๋ ๋ฒ์งธ๋ก ํฐ ์ํ์ D๋ก ์ฎ๊ธฐ๊ธฐ
์ ๊ณผ์ ์ ์ฌ๊ท์ ์ผ๋ก ์์ฑํ๋ฉด ๋๋๋ฐ, 1๋ฒ ๊ณผ์ ์ ์๋ ํ๋ฒํ ํ๋ ธ์ด ํ ๋ฌธ์ ์ฒ๋ผ ์ฎ๊ธฐ๊ณ , 2, 3, 4๋ฒ ๊ณผ์ ์ ์ํ์ ํ๋์ฉ ์ด๋ํ๋ ๊ฑฐ๋๊น ๊ทธ๋ฅ ๊ทธ๋๋ก ์ฎ๊ธฐ๋ฉด ๋๋ค. N์ ํฌ๊ธฐ๋ฅผ 2์ฉ ์ค์ฌ๋๊ฐ๋ฏ๋ก base condition์ N์ด 1์ผ ๋์ 2์ผ ๋ ๋ชจ๋๋ฅผ ๊ณ ๋ คํด์ผ ํจ.
์ฝ๋
๋๋ณด๊ธฐ
import java.io.*;
public class Main {
public static StringBuilder sb = new StringBuilder();
public static int M;
public static void hanoi(int N, char from, char to, char rest) {
if (N == 1) {
move(from, to);
return;
}
hanoi(N - 1, from, rest, to);
hanoi(1, from, to, rest);
hanoi(N - 1, rest, to, from);
}
public static void dHanoi(int N, char from, char to, char rest1, char rest2) {
if (N == 1) {
move(from, to);
return;
} else if (N == 2) {
move(from, rest2);
move(from, to);
move(rest2, to);
return;
}
hanoi(N - 2, from, rest1, rest2); // 1. (N - 2)๊ฐ๋ฅผ D๊ฐ ์๋ ๊ธฐ๋ฅ์ผ๋ก ์ฎ๊ธฐ๊ธฐ
move(from, rest2); // 2. ๋ ๋ฒ์งธ๋ก ํฐ ์ํ์ D๊ฐ ์๋ ๋น์ด์๋ ๊ธฐ๋ฅ์ผ๋ก ์ฎ๊ธฐ๊ธฐ
move(from, to); // 3. ๊ฐ์ฅ ํฐ ์ํ์ D๋ก ์ฎ๊ธฐ๊ธฐ
move(rest2, to); // 4. ๋ ๋ฒ์งธ๋ก ํฐ ์ํ์ D๋ก ์ฎ๊ธฐ๊ธฐ
dHanoi(N - 2, rest1, to, from, rest2);
}
public static void move(char from, char to) {
sb.append(from).append(' ').append(to).append('\n');
M++;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
dHanoi(N, 'A', 'D', 'B', 'C');
System.out.println(M);
System.out.println(sb);
br.close();
}
}
'Problem Solving' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Java] ๋ฐฑ์ค 16946 - ๋ฒฝ ๋ถ์๊ณ ์ด๋ํ๊ธฐ 4 (0) | 2024.02.29 |
---|---|
[Java] ๋ฐฑ์ค 31091 - ๊ฑฐ์ง๋ง (0) | 2024.02.23 |
[Java] ๋ฐฑ์ค 31423 - ์ ์ด ํตํํฉ ๊ณํ (0) | 2024.02.21 |
[C++] ๋ฐฑ์ค 17073 - ๋๋ฌด ์์ ๋น๋ฌผ (0) | 2023.02.04 |
[Java] ๋ฐฑ์ค 1406 - ์๋ํฐ (0) | 2022.02.05 |