๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Problem Solving

[Java] ๋ฐฑ์ค€ 31248 - 3+1 ํ•˜๋…ธ์ด ํƒ‘

๋ฌธ์ œ

 

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();
	}
}