示例#1
0
        public void GraphIntv_CloneGraphTest1()
        {
            UndirectedGraphNode t0 = new UndirectedGraphNode(0),
           t1 = new UndirectedGraphNode(1),
           t2 = new UndirectedGraphNode(2);

            t0.Neighbors.Add(t1);
            t0.Neighbors.Add(t2);
            t1.Neighbors.Add(t0);
            t1.Neighbors.Add(t2);
            t2.Neighbors.Add(t0);
            t2.Neighbors.Add(t1);
            t2.Neighbors.Add(t2);

            UndirectedGraphNode r = CloneGraph(t0);

            Assert.AreEqual(0, r.Label);
            Assert.AreEqual(2, r.Neighbors.Count);

            UndirectedGraphNode r1 = r.Neighbors[0];

            Assert.AreEqual(1, r1.Label);
            Assert.AreEqual(2, r1.Neighbors.Count);

            UndirectedGraphNode r2 = r.Neighbors[1];

            Assert.AreEqual(2, r2.Label);
            Assert.AreEqual(3, r2.Neighbors.Count);
        }
示例#2
0
        public static UndirectedGraphNode CloneGraph(UndirectedGraphNode node)
        {
            if (node == null)
            {
                return(null);
            }

            Queue <UndirectedGraphNode> q   = new Queue <UndirectedGraphNode>();
            UndirectedGraphNode         ret = new UndirectedGraphNode(node.Label);

            ret.Neighbors = node.Neighbors;
            Dictionary <UndirectedGraphNode, UndirectedGraphNode> umap =
                new Dictionary <UndirectedGraphNode, UndirectedGraphNode>();

            umap[node] = ret;

            q.Enqueue(ret);
            while (q.Count != 0)
            {
                List <UndirectedGraphNode> v = new List <UndirectedGraphNode>();
                UndirectedGraphNode        n = q.Dequeue();
                foreach (UndirectedGraphNode k in n.Neighbors)
                {
                    if (umap.ContainsKey(k))
                    {
                        v.Add(umap[k]);
                    }
                    else
                    {
                        UndirectedGraphNode a = new UndirectedGraphNode(k.Label);
                        a.Neighbors = k.Neighbors;
                        v.Add(a);
                        q.Enqueue(a);
                        umap[k] = a;
                    }
                }

                n.Neighbors = v;
            }

            return(ret);
        }