Home 11729. 하노이 탑 이동 순서
Post
Cancel

11729. 하노이 탑 이동 순서

문제

제한조건 첫째 줄에 첫 번째 장대에 쌓인 원판의 개수 N (1 ≤ N ≤ 20)이 주어진다.

입출력 예시

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;

internal class Program
{
	static void Main(string[] args)
	{
		int input = int.Parse(Console.ReadLine());

		int moveCnt = Convert.ToInt32(Math.Pow(2, input)) - 1;
		Console.WriteLine(moveCnt);

		Move(input, 0, 2);
	}

	static void Move(int currentPoint, int start, int toPoint)
	{
		if (currentPoint == 1)
		{
			Console.WriteLine($"{start + 1} {toPoint + 1} ");
			return;
		}

		int otherPoint = 3 - (start + toPoint);

		Move(currentPoint - 1, start, otherPoint);
		Move(1, start, toPoint);
		Move(currentPoint - 1, otherPoint, toPoint);
	}
}

[실패]. 시간초과

  • 데이터 출력 시 +1하는 작업을 제거 하기 위해 시작 점을 1~3으로 두고, 중간 지점 구하는 값도 6에서 빼주도록 함
  • 출력해야 할 값을 StringBuilder에 전부 저장하고, 마지막에 한번에 출력하도록 수정함
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;

internal class Program
{
	static void Main(string[] args)
	{
		int input = int.Parse(Console.ReadLine());

		int moveCnt = Convert.ToInt32(Math.Pow(2, input)) - 1;
		Console.WriteLine(moveCnt);

		StringBuilder sboPrint = new StringBuilder();
		Move(input, 1, 3, sboPrint);

        Console.WriteLine(sboPrint.ToString());
    }

	static void Move(int currentPoint, int start, int end, StringBuilder sboPrint)
	{
		if (currentPoint == 1)
		{
			sboPrint.AppendFormat("{0} {1}\n", start, end);
			return;
		}

		int other = 6 - (start + end);

		Move(currentPoint - 1, start, other, sboPrint);
		Move(1, start, end, sboPrint);
		Move(currentPoint - 1, other, end, sboPrint);
	}
}

[성공] ⇒ 인덱스는 상관 없고, 출력이 문제 였던 것 같긴 함


백준에서 문제 확인

This post is licensed under CC BY 4.0 by the author.