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 / \ \_/
这题的思路主要用到Queue和Map
Queue用来做BFS,逐一遍历所有的node,Map用来存放所有原始Graph中node的拷贝,有了这个之后每次只需要判断一下Map中有没有当前遍历的neighbor,如果有,直接让放入他的拷贝到新的当前node的拷贝中。如果没有,放入一份该neighbor的拷贝到Map中,同时将该neighbor放入Queue,因为这是第一次遍历这个neighbor。
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null)
return node;
Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>();
q.add(node);
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
map.put(node, newNode);
while (!q.isEmpty()) {
UndirectedGraphNode cur = q.poll();
List<UndirectedGraphNode> curNeighbors = cur.neighbors;
for (UndirectedGraphNode neighbor : curNeighbors) {
if (!map.containsKey(neighbor)) {
UndirectedGraphNode copy = new UndirectedGraphNode(neighbor.label);
map.put(neighbor, copy);
q.add(neighbor);
map.get(cur).neighbors.add(copy);
} else {
map.get(cur).neighbors.add(map.get(neighbor));
}
}
}
return map.get(node);
}