코딩테스트 연습 스터디 진행중 입니다. ✍✍✍
Notion : https://www.notion.so/1c911ca6572e4513bd8ed091aa508d67
문제
https://www.acmicpc.net/problem/11729
[나의 풀이]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Correct_answer {
// 하노이 탑 이동
static StringBuilder move(int n, int x, int y, String ans, StringBuilder sb) throws IOException {
if (n > 0) {
sb = move(n - 1, x, 6 - x - y, ans, sb);
sb.append(x + " " + y + "\n");
// 3,1,3
// 2,1,2
// 1,1,3
// 2,1,2
// 1,3,2
// 3,1,3
// 3,1,3
// 2,2,3
// 1,2,1
// 2,2,3
// 1,1,3
}
if (n > 0) {
sb = move(n - 1, 6 - x - y, y, ans, sb);
}
return sb;
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 속도 향상을 위해 StringBuilder 사용!
StringBuilder sb = new StringBuilder();
String ans = "";
int cnt = 0;
int n = Integer.parseInt(br.readLine());
sb = move(n, 1, 3, ans, sb);
// 이동 횟수 체크
char blank = ' ';
for (int i = 0; i < sb.length(); i++) {
char line = sb.charAt(i);
if (line == blank) {
cnt++;
}
}
System.out.println(cnt);
System.out.println(sb.toString());
}
}
하노이 탑 이동은 크게 3단계로 이루어집니다.
이에 대한 메서드가 move(원판no,시작기둥,목표기둥) 이고 재귀함수로 구현했습니다. 🐤🐤🐤
출력 시에 시간초과가 나서 고생하였는데 String 객체에 계속해서 x+" "+y+"\n"을 더하는 과정에서 오래걸리는 듯하였습니다.
그리하여 StrignBuilder를 활용하여 append()하고 출력하시는 방식으로 바꾸어 해결할 수 있었습니다. 앞으로 빠른 String 객체를 연산이 필요할 때는 StringBuilder를 활용해야겠습니다!
감사합니다!🐮🐮🐮