Leetcode 133: Clone Graph
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
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
/ \
\_/
1 /** 2 * Definition for undirected graph. 3 * public class UndirectedGraphNode { 4 * public int label; 5 * public IList<UndirectedGraphNode> neighbors; 6 * public UndirectedGraphNode(int x) { label = x; neighbors = new List<UndirectedGraphNode>(); } 7 * }; 8 */ 9 10 public class Solution { 11 public UndirectedGraphNode CloneGraph(UndirectedGraphNode node) { 12 if (node == null) return null; 13 14 var root = new UndirectedGraphNode(node.label); 15 var visited = new Dictionary<int, UndirectedGraphNode>(); 16 visited[root.label] = root; 17 18 DFS(node, root, visited); 19 20 return root; 21 } 22 23 private void DFS(UndirectedGraphNode node, UndirectedGraphNode clone, Dictionary<int, UndirectedGraphNode> visited) 24 { 25 if (node == null) return; 26 27 foreach (var n in node.neighbors) 28 { 29 // note: because graph can have cycle, we need to make sure to not creating the node multi-times 30 if (visited.ContainsKey(n.label)) 31 { 32 clone.neighbors.Add(visited[n.label]); 33 } 34 else 35 { 36 var c = new UndirectedGraphNode(n.label); 37 clone.neighbors.Add(c); 38 visited[n.label] = c; 39 DFS(n, c, visited); 40 } 41 } 42 } 43 }

浙公网安备 33010602011771号