본문 바로가기

Algorithm/Baekjoon

[백준_JAVA_알고리즘] 11729 하노이 탑 이동 순서

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {
	static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));
	
	public static void main(String[] args) throws IOException {
		String line = bufferedReader.readLine();
		int N = Integer.parseInt(line);
		bufferedReader.close();
		
		bufferedWriter.write((int) (Math.pow(2, N) - 1) + "\n");
		
		hanoi_tower(N, 1, 2, 3);

		bufferedWriter.flush();
		bufferedWriter.close();
	}
	/*
	 * 3 1 2 3
	 * 2 1 3 2
	 * 1 2 1 3
	 */
	public static void hanoi_tower(int n, int from, int tmp, int to) throws IOException {
		if(n == 1) {
			bufferedWriter.write(from+" "+to+" "+"\n");
			return;
		}
		else {
			hanoi_tower(n-1, from, to, tmp);
			bufferedWriter.write(from+" "+to+" "+"\n");
			hanoi_tower(n-1, tmp, from, to);
		}
	}
}
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class Main {
	static Scanner scanner = new Scanner(System.in);
	static BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));
	
	public static void main(String[] args) throws IOException {
		int N = scanner.nextInt();
		bufferedWriter.write((int) (Math.pow(2, N) - 1) + "\n");
		
		hanoi_tower(N, 1, 2, 3);
		
		scanner.close();

		bufferedWriter.flush();
		bufferedWriter.close();
	}
	/*
	 * 3 1 2 3
	 * 2 1 3 2
	 * 1 2 1 3
	 */
	public static void hanoi_tower(int n, int from, int tmp, int to) throws IOException {
		if(n == 1) {
			bufferedWriter.write(from+" "+to+" "+"\n");
			return;
		}
		else {
			hanoi_tower(n-1, from, to, tmp);
			bufferedWriter.write(from+" "+to+" "+"\n");
			hanoi_tower(n-1, tmp, from, to);
		}
	}
}

다음 하노이탑 문제는 막대 1->3으로 이동하는 예제이다. 한 번에 하나의 원판을 옮길 수 있고, 중간에 임시로 저장할 막대 공간이 필요하다. 매개변수 n은 원판의 개수, from은 출발지, tmp는 임시 저장 막대, to는 목적지이다.

 

처음에 BufferedReader을 사용했을 때, 런타임 오류가 발생했다. 검색을 해보니, 입력 종료 문제였다. EOF를 잘 처리해야 하는데, bufferedReader가 정상적으로 종료되지 않으면 발생할 수 있다. 따라서 EOF 처리를 통해 해결할 수 있었다. 단, Scanner는 자동으로 EOF를 감지하고 처리한다.