staafl

three jugs problem with DFS

Oct 9th, 2013
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class Program
  5. {
  6. static void Main()
  7. {
  8. var moves = Poisson(new[] { 3, 5, 8 }, new[] { 0, 0, 8 }, 4);
  9. if (moves == null)
  10. Console.WriteLine("No solution!");
  11. else
  12. foreach (var move in moves)
  13. Console.WriteLine("{0} --> {1}, quantity: {2}", move.Item1, move.Item2, move.Item3);
  14. }
  15.  
  16. static List<Tuple<int, int, int>> Poisson(
  17. int[] max,
  18. int[] now,
  19. int goal, // d
  20. List<Tuple<int, int, int>> moves = null,
  21. HashSet<Tuple<int, int, int>> seen = null)
  22. {
  23.  
  24. moves = moves ?? new List<Tuple<int, int, int>>();
  25. seen = seen ?? new HashSet<Tuple<int, int, int>>();
  26.  
  27. // been here before?
  28. if (!seen.Add(Tuple.Create(now[0], now[1], now[2])))
  29. return null;
  30.  
  31. // check for success
  32. for (int ii = 0; ii < now.Length; ++ii)
  33. if (now[ii] == goal)
  34. return moves;
  35.  
  36. for (int from = 0; from < now.Length; ++from)
  37. for (int to = 0; to < now.Length; ++to)
  38. {
  39.  
  40. if (from == to || now[from] == 0 || now[to] == max[to])
  41. continue;
  42.  
  43. int qty = Math.Min(max[to] - now[to], now[from]);
  44.  
  45. // pour from --> to
  46.  
  47. now[to] += qty;
  48. now[from] -= qty;
  49.  
  50. moves.Add(Tuple.Create(from, to, qty));
  51. if (Poisson(max, now, goal, moves, seen) != null)
  52. return moves;
  53.  
  54. // revert move
  55. now[from] += qty;
  56. now[to] -= qty;
  57. moves.RemoveAt(moves.Count - 1);
  58. }
  59.  
  60. // failed
  61. return null;
  62. }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment