Clone an undirected graph. each node in the graph containslabel
And 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#
.
- First node is labeled
0
. Connect Node0
To both nodes1
And2
.
- Second node is labeled
1
. Connect Node1
To Node2
.
- Third node is labeled
2
. Connect Node2
To Node2
(Itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / / 0 --- 2 / \_/
Topic: clone a graph using the DFS recursive method, and use hashmap to save the ing between the nodes in the source image and those in the new graph. In addition, this hashmap can be used to determine whether a node has been cloned in O (1) time, and know the new node it has been cloned.
To implement a clone node method, in this method:
- Determine whether the node has been cloned. If yes, return the corresponding clone node;
- If the node has not been cloned, create a new node as the clone node of the node and recursively clone its neighbor node into the neighbors list of the node;
The Code is as follows:
1 /** 2 * Definition for undirected graph. 3 * class UndirectedGraphNode { 4 * int label; 5 * List<UndirectedGraphNode> neighbors; 6 * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } 7 * }; 8 */ 9 public class Solution {10 private HashMap<UndirectedGraphNode,UndirectedGraphNode> mapClone = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();11 12 private UndirectedGraphNode cloneNode(UndirectedGraphNode node){13 if(node == null)14 return null;15 //if this node already has a clone16 if(mapClone.containsKey(node))17 return mapClone.get(node);18 19 //if this node hasn‘t been cloned, we construct a new node copy20 UndirectedGraphNode copy = new UndirectedGraphNode(node.label);21 mapClone.put(node, copy);22 23 //clone all the neighbers of node24 for(UndirectedGraphNode n:node.neighbors){25 copy.neighbors.add(cloneNode(n));26 }27 return copy;28 }29 public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {30 return cloneNode(node);31 }32 }