Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use
#
as a separator for each node, and
,
as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph{0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by#.
- First node is labeled as
0. Connect node0to both nodes1and2. - Second node is labeled as
1. Connect node1to node2. - Third node is labeled as
2. Connect node2to node2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
Answer:https://leetcode.com/problems/clone-graph/description/#
/**
* Definition for undirected graph.
* public class UndirectedGraphNode {
* public int label;
* public IList<UndirectedGraphNode> neighbors;
* public UndirectedGraphNode(int x) { label = x; neighbors = new List<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode CloneGraph(UndirectedGraphNode node) {
if (node == null)
{
return node;
}
// use bfs algorithm to traverse the graph and get all nodes.
List<UndirectedGraphNode> nodes = getNodes(node);
// copy nodes, store the old->new mapping information in a hash map
Dictionary<UndirectedGraphNode, UndirectedGraphNode> mapping = new Dictionary<UndirectedGraphNode, UndirectedGraphNode>();
foreach (UndirectedGraphNode n in nodes)
{
mapping[n] = new UndirectedGraphNode(n.label);
}
// copy neighbors(edges)
foreach (UndirectedGraphNode n in nodes)
{
UndirectedGraphNode newNode = mapping[n];
foreach (UndirectedGraphNode neighbor in n.neighbors)
{
UndirectedGraphNode newNeighbor = mapping[neighbor];
newNode.neighbors.Add(newNeighbor);
}
}
return mapping[node];
}
private List<UndirectedGraphNode> getNodes(UndirectedGraphNode node)
{
Queue<UndirectedGraphNode> queue = new Queue<UndirectedGraphNode>();
HashSet<UndirectedGraphNode> set = new HashSet<UndirectedGraphNode>();
queue.Enqueue(node);
set.Add(node);
while (queue.Count > 0)
{
UndirectedGraphNode head = queue.Dequeue();
foreach (UndirectedGraphNode neighbor in head.neighbors)
{
if (!set.Contains(neighbor))
{
set.Add(neighbor);
queue.Enqueue(neighbor);
}
}
}
return new List<UndirectedGraphNode>(set); //or set.ToList()
}
}