Guest User

Untitled

a guest
Mar 22nd, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace CloneGraph
  8. {
  9. /// <summary>
  10. /// Leetcode 133: clone graph
  11. /// March 13, 2018
  12. /// </summary>
  13. class Program
  14. {
  15. static void Main(string[] args)
  16. {
  17. }
  18.  
  19. public class UndirectedGraphNode {
  20. public int label;
  21. public IList<UndirectedGraphNode> neighbors;
  22. public UndirectedGraphNode(int x) {
  23. label = x;
  24. neighbors = new List<UndirectedGraphNode>();
  25. }
  26. };
  27.  
  28. public UndirectedGraphNode CloneGraph(UndirectedGraphNode node)
  29. {
  30. if (node == null)
  31. {
  32. return null;
  33. }
  34.  
  35. var queue = new Queue<UndirectedGraphNode>();
  36. var map = new Dictionary<UndirectedGraphNode, UndirectedGraphNode>();
  37.  
  38. var newHead = new UndirectedGraphNode(node.label);
  39.  
  40. queue.Enqueue(node);
  41. map.Add(node, newHead);
  42.  
  43. while (queue.Count > 0)
  44. {
  45. var curr = (UndirectedGraphNode)queue.Dequeue();
  46.  
  47. var currNeighbors = curr.neighbors;
  48.  
  49. foreach (UndirectedGraphNode neighbor in currNeighbors)
  50. {
  51. if (!map.ContainsKey(neighbor))
  52. {
  53. var copy = new UndirectedGraphNode(neighbor.label);
  54.  
  55. map.Add(neighbor, copy);
  56.  
  57. map[curr].neighbors.Add(copy);
  58.  
  59. queue.Enqueue(neighbor);
  60. }
  61. else
  62. {
  63. map[curr].neighbors.Add(map[neighbor]);
  64. }
  65. }
  66. }
  67.  
  68. return newHead;
  69. }
  70. }
  71. }
Add Comment
Please, Sign In to add comment