Example #1
0
 public UndirectedGraphNode CloneGraph(UndirectedGraphNode node)
 {
     if (node == null)
     {
         return(null);
     }
     return(CloneNode(node, new Dictionary <int, UndirectedGraphNode>()));
 }
Example #2
0
        private UndirectedGraphNode CloneNode(UndirectedGraphNode node, Dictionary <int, UndirectedGraphNode> clones)
        {
            if (clones.ContainsKey(node.label))
            {
                return(clones[node.label]);
            }

            var clone = new UndirectedGraphNode(node.label);

            clones.Add(clone.label, clone);

            foreach (var neighbor in node.neighbors)
            {
                clone.neighbors.Add(CloneNode(neighbor, clones));
            }

            return(clone);
        }
Example #3
0
        public void CloneUndirectedGraphTests()
        {
            var root  = new UndirectedGraphNode(1);
            var node2 = new UndirectedGraphNode(2);

            root.neighbors.Add(node2);
            node2.neighbors.Add(root);

            var node3 = new UndirectedGraphNode(3);

            root.neighbors.Add(node3);
            node3.neighbors.Add(root);

            node2.neighbors.Add(node3);
            node3.neighbors.Add(node2);

            node3.neighbors.Add(node3);

            var clone = root.CloneGraph(root);

            Assert.IsNotNull(clone);
            Assert.AreEqual(2, clone.neighbors.Count);
        }