/**
* Steps to clone a graph.
* i. clone all nodes in the graph
* ii. clone all neighbors for the new nodes
* we need a hashmap to save the mapping of old and new nodes,
* then we can copy all neighbors for a new node.
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) return node;
// get all nodes using BFS
HashSet<UndirectedGraphNode> nodes = cloneNodes(node);
// create a mapping from old node to new node so that we can clone all edges in teh graph
HashMap<UndirectedGraphNode, UndirectedGraphNode> mapping = new HashMap<>();
for (UndirectedGraphNode n : nodes) {
UndirectedGraphNode newNode = new UndirectedGraphNode(n.label);
mapping.put(n, newNode);
}
// clone all neighbors from old nodes for the new nodes
for (UndirectedGraphNode n : nodes) {
UndirectedGraphNode newNode = mapping.get(n);
for (UndirectedGraphNode neighbor : n.neighbors) {
UndirectedGraphNode newNeighbor = mapping.get(neighbor);
newNode.neighbors.add(newNeighbor);
}
}
return mapping.get(node);
}
// use BFS to get all nodes in the graph, nodes are unique
private static HashSet<UndirectedGraphNode> cloneNodes(UndirectedGraphNode node) {
HashSet<UndirectedGraphNode> set = new HashSet<>();
Queue<UndirectedGraphNode> queue = new LinkedList<>();
queue.offer(node);
set.add(node);
while (!queue.isEmpty()) {
UndirectedGraphNode n = queue.poll();
for (UndirectedGraphNode neighbor : n.neighbors) {
if (set.add(neighbor)) {
queue.offer(neighbor);
}
}
}
return set;
}
}
Leetcode 133. Clone Graph
最新推荐文章于 2021-05-14 10:42:19 发布