fork(1) download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Test
  5. {
  6. class Move
  7. {
  8. public uint Number { get; private set; }
  9.  
  10. public char Src { get; private set; }
  11.  
  12. public char Dest { get; private set; }
  13.  
  14. public char Alt { get; private set; }
  15.  
  16. public Move(uint number, char src, char dest, char alt)
  17. {
  18. this.Number = number;
  19. this.Src = src;
  20. this.Alt = alt;
  21. this.Dest = dest;
  22. }
  23. }
  24.  
  25. static void TowersIterative(uint number, char src, char dest, char alt)
  26. {
  27. var stack = new Stack<Move>();
  28.  
  29. stack.Push(new Move(number, src, dest, alt));
  30. while (stack.Count != 0)
  31. {
  32. var move = stack.Pop();
  33. if (move.Number == 1)
  34. Console.WriteLine("Move one disc from {0} to {1}", move.Src, move.Dest);
  35. else
  36. {
  37. stack.Push(new Move(move.Number - 1, move.Alt, move.Dest, move.Src));
  38. stack.Push(new Move(1, move.Src, move.Dest, move.Alt));
  39. stack.Push(new Move(move.Number - 1, move.Src, move.Alt, move.Dest));
  40. }
  41. }
  42. }
  43.  
  44. public static void Main()
  45. {
  46. TowersIterative(3, 'L', 'M', 'R');
  47. }
  48. }
Success #stdin #stdout 0.03s 33952KB
stdin
Standard input is empty
stdout
Move one disc from L to M
Move one disc from L to R
Move one disc from M to R
Move one disc from L to M
Move one disc from R to L
Move one disc from R to M
Move one disc from L to M