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 node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
直接用HashMap来做应该是最简单的,这个对十字链表也可以。使用hashmap来存储node的对应关系。
1 /** 2 * Definition for undirected graph. 3 * class UndirectedGraphNode { 4 * int label; 5 * ArrayListneighbors; 6 * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList (); } 7 * }; 8 */ 9 public class Solution {10 HashMap map = new HashMap ();11 public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {12 map.clear();13 return cloneNode(node);14 }15 16 private UndirectedGraphNode cloneNode(UndirectedGraphNode node)17 {18 if (node == null) return null;19 if (map.containsKey(node)) return map.get(node);20 else21 {22 UndirectedGraphNode copy = new UndirectedGraphNode(node.label);23 map.put(node, copy);24 for (UndirectedGraphNode n : node.neighbors)25 {26 copy.neighbors.add(cloneNode(n));27 }28 return copy;29 }30 }31 }