Last active
January 8, 2016 08:41
-
-
Save oyakodon/479afe2312326b52d627 to your computer and use it in GitHub Desktop.
ハノイの塔を解きます。 / C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Hanoi | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int num; | |
Console.WriteLine("- ハノイの塔 -"); | |
Console.WriteLine("円盤の枚数を入力してください。\n"); | |
Console.Write(">"); | |
int.TryParse(Console.ReadLine(), out num); | |
if (num != 0) | |
{ | |
Console.WriteLine("移動回数: " + Hanoi(num, "A", "C", "B")); | |
Console.WriteLine("移動回数(計算式使用): " + Hanoi(num)); | |
} else | |
{ | |
Console.WriteLine("入力された値が適切ではありません。"); | |
} | |
} | |
/// <summary> | |
/// ハノイの塔の最小移動回数のみを計算する。 | |
/// </summary> | |
/// <param name="n">円盤の枚数</param> | |
static int Hanoi(int n) | |
{ | |
return (int)Math.Pow(2.0, n) - 1; | |
} | |
/// <summary> | |
/// ハノイの塔を解く。 | |
/// 再帰使用。↑のオーバーロード。 | |
/// </summary> | |
/// <param name="n">円盤の枚数</param> | |
/// <param name="from">最初にn枚の円盤がある杭の名前</param> | |
/// <param name="to">円盤を移動させたい杭の名前</param> | |
/// <param name="working">一時的に利用する杭の名前</param> | |
/// <returns>移動回数</returns> | |
static int Hanoi(int n, string from, string to, string working) | |
{ | |
if (n != 1) | |
{ | |
var move = 0; | |
move += Hanoi(n - 1, from, working, to); | |
Move(n, from, to); | |
move += Hanoi(n - 1, working, to, from); | |
return move + 1; | |
} else | |
{ | |
Move(n, from, to); | |
return 1; | |
} | |
} | |
/// <summary> | |
/// [From]から[To]へ円盤を移動させる動作。 | |
/// </summary> | |
/// <param name="n">円盤の大きさ</param> | |
/// <param name="from">移動元の杭</param> | |
/// <param name="to">移動先の杭</param> | |
static void Move(int n,string from, string to) | |
{ | |
Console.WriteLine(n + "番の円盤を [" + from + "] から [" + to + "] へ移動。"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment