Clone Graph
描述
Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbours
.
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 neighbour 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 node 0 to both nodes 1 and 2.
- Second node is labeled as 1. Connect node 1 to node 2.
- Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
分析
广度优先遍历或深度优先遍历都可以。
DFS
// Clone Graph
// DFS,时间复杂度O(n),空间复杂度O(n)
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) return null;
// key is original node,value is copied node
HashMap<UndirectedGraphNode, UndirectedGraphNode> visited = new HashMap<>();
clone(node, visited);
return visited.get(node);
}
// DFS
private static UndirectedGraphNode clone(UndirectedGraphNode node,
HashMap<UndirectedGraphNode,
UndirectedGraphNode> visited) {
// a copy already exists
if (visited.containsKey(node)) return visited.get(node);
UndirectedGraphNode new_node = new UndirectedGraphNode(node.label);
visited.put(node, new_node);
for (UndirectedGraphNode nbr : node.neighbors)
new_node.neighbors.add(clone(nbr, visited));
return new_node;
}
}
BFS
// Clone Graph
// BFS,时间复杂度O(n),空间复杂度O(n)
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) return null;
// key is original node,value is copied node
HashMap<UndirectedGraphNode,UndirectedGraphNode> visited = new HashMap<>();
// each node in queue is already copied itself
// but neighbors are not copied yet
Queue<UndirectedGraphNode> q = new LinkedList<>();
q.offer(node);
visited.put(node, new UndirectedGraphNode(node.label));
while (!q.isEmpty()) {
UndirectedGraphNode cur = q.poll();
for (UndirectedGraphNode nbr : cur.neighbors) {
// a copy already exists
if (visited.containsKey(nbr)) {
visited.get(cur).neighbors.add(visited.get(nbr));
} else {
UndirectedGraphNode new_node =
new UndirectedGraphNode(nbr.label);
visited.put(nbr, new_node);
visited.get(cur).neighbors.add(new_node);
q.offer(nbr);
}
}
}
return visited.get(node);
}
}
原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/graph/clone-graph.html