Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- public class Program
- {
- public static void Main(String[] args)
- {
- Hanoi(3);
- }
- private static Stack<Int32>[] towers = new Stack<int>[3];
- public static void Hanoi(int count)
- {
- ringsCount = count; iterationsCount = 0;
- towers[0] = new Stack<int>();
- for (int i = 0; i < count; i++)
- towers[0].Push(count - i);
- towers[1] = new Stack<int>();
- towers[2] = new Stack<int>();
- Move(count, towers[0], towers[1], towers[2]);
- WriteTowers();
- }
- private static int ringsCount, iterationsCount;
- private static void Move(int q, Stack<Int32> from, Stack<Int32> to, Stack<Int32> buf)
- {
- if (q > 0)
- {
- Move(q - 1, from, buf, to);
- WriteTowers();
- iterationsCount++;
- int disk = from.Peek();
- from.Pop();
- to.Push(disk);
- Move(q - 1, buf, to, from);
- }
- }
- private static void WriteTowers()
- {
- var strings = new string[ringsCount];
- foreach (var tower in towers)
- {
- int i = 0;
- while (i < ringsCount - tower.Count)
- {
- strings[i] += "| ";
- i++;
- }
- foreach (int ring in tower)
- {
- strings[i] += ring.ToString() + " ";
- i++;
- }
- }
- Console.WriteLine("Шаг № {0}:", iterationsCount);
- foreach (string str in strings)
- Console.WriteLine(str);
- Console.WriteLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement