示例#1
0
 public static GraphNode Clone(GraphNode graph)
 {
     if (graph == null) return null;
     Dictionary<GraphNode, GraphNode> visited = new Dictionary<GraphNode, GraphNode>();
     Queue<GraphNode> queue = new Queue<GraphNode>();
     queue.Enqueue(graph);
     GraphNode copy = new GraphNode(graph.value);
     visited[graph] = copy;
     while (queue.Count > 0)
     {
         GraphNode node = queue.Dequeue();
         foreach (GraphNode neighbor in node.neighbors)
         {
             if (visited.ContainsKey(neighbor)) // not exisited
             {
                 GraphNode n = new GraphNode();
                 visited[node].neighbors.Add(n);
                 visited[neighbor] = n;
                 queue.Enqueue(neighbor);
             }
             else
             {
                 visited[node].neighbors.Add(visited[neighbor]);
             }
         }
     }
     return copy;
 }
示例#2
0
 public static void Test()
 {
     GraphNode node1 = new GraphNode(1);
     GraphNode node2 = new GraphNode(2);
     GraphNode node3 = new GraphNode(3);
     GraphNode node4 = new GraphNode(4);
     GraphNode node5 = new GraphNode(5);
     node1.neighbors.Add(node2);
     node1.neighbors.Add(node3);
     node2.neighbors.Add(node4);
     node2.neighbors.Add(node5);
     node3.neighbors.Add(node5);
     node3.neighbors.Add(node4);
     node1.DFS();
     GraphNode copy = Clone(node1);
     copy.DFS();
 }