Guest User

Untitled

a guest
Jan 23rd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. using System;
  2.  
  3. class Solution
  4. {
  5. public class Node
  6. {
  7. public int cost;
  8. public Node[] children;
  9. //public Node parent;
  10.  
  11. public Node(int val)
  12. {
  13. cost = val;
  14. }
  15. }
  16.  
  17. public static int getCheapestCost(Node rootNode)
  18. {
  19. if(rootNode == null) // false
  20. {
  21. return 0;
  22. }
  23.  
  24. var rootValue = rootNode.cost; // 0
  25. var children = rootNode.children; // 3
  26.  
  27. // base case
  28. if(rootNode.children == null) // reach leaf node 4, 1, 10, 1, 5
  29. {
  30. return rootValue;
  31. }
  32.  
  33. // recurrence
  34. int minPathOfChildren = Int32.MaxValue;
  35.  
  36. foreach(var child in children)
  37. {
  38. var currentPath = getCheapestCost(child); // 9, 7, 7
  39.  
  40. minPathOfChildren = currentPath < minPathOfChildren? currentPath : minPathOfChildren; // 7
  41. }
  42.  
  43. return rootValue + minPathOfChildren; // 0 + 7
  44.  
  45. }
  46.  
  47. static void Main(string[] args)
  48. {
  49.  
  50. Node root = new Node(0);
  51.  
  52. Node node1 = new Node(5);
  53. Node node2 = new Node(3);
  54. Node node3 = new Node(6);
  55.  
  56. Node node11 = new Node(5);
  57. Node node12 = new Node(4);
  58.  
  59. Node node21 = new Node(7);
  60. Node node22 = new Node(5);
  61.  
  62. Node node31 = new Node(6);
  63. Node node32 = new Node(7);
  64.  
  65.  
  66. root.children = new Node[3];
  67. root.children[0] = node1;
  68. root.children[1] = node2;
  69. root.children[2] = node3;
  70.  
  71. root.children[0].children = new Node[2];
  72. root.children[1].children = new Node[2];
  73. root.children[2].children = new Node[2];
  74.  
  75. root.children[0].children[0] = node11;
  76. root.children[0].children[1] = node12;
  77.  
  78. root.children[1].children[0] = node21;
  79. root.children[1].children[1] = node22;
  80.  
  81. root.children[2].children[0] = node31;
  82. root.children[2].children[1] = node32;
  83.  
  84. Console.WriteLine(getCheapestCost(root));
  85. }
  86. }
  87.  
  88. /*
  89.  
  90. Go over all the paths
  91. 0->5->4 9
  92. 0->3->2->1->1 7
  93. 0->3->0->10 13
  94. 0->6->1 7
  95. 0->6->5 11
  96.  
  97. Find minimum value
  98. total 5 paths, not path itself, need minimum sales path -> Math.min(9, 7, 13, 7, 11) -> minimum 7
  99.  
  100. DFS search:
  101. depth first search -> recursive
  102.  
  103. Template:
  104. if the node is null
  105. return 0
  106.  
  107. base case
  108. if there is no child
  109. return node.value
  110.  
  111. // have multiple child
  112. minPath = Int.Max
  113. foreach child
  114. fidnMinPath
  115. update minPath
  116.  
  117. return node.value + minPath
  118.  
  119. recurrence formula
  120.  
  121. Write code
  122. */
Add Comment
Please, Sign In to add comment