Clone Graph
Description
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. Nodes are labeled uniquely.
You need to return a deep copied graph, which has the same structure as the original graph, and any changes to the new graph will not have any effect on the original graph
/**
* Definition for Undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) {
* label = x;
* neighbors = new ArrayList<UndirectedGraphNode>();
* }
* }
*/
public class Solution {
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
// write your code here
if(node == null){
return null ;
}
ArrayList<UndirectedGraphNode> nodes = getNodes(node) ;
Map<UndirectedGraphNode,UndirectedGraphNode> mapping = new HashMap<>();
for(UndirectedGraphNode n : nodes){
mapping.put(n , new UndirectedGraphNode(n.label));
}
for(UndirectedGraphNode n : nodes){
UndirectedGraphNode newnodes = mapping.get(n) ;
for(UndirectedGraphNode neighbor : n.neighbors){
UndirectedGraphNode newneighbors = mapping.get(neighbor) ;
newnodes.neighbors.add(newneighbors);
}
}
return mapping.get(node); //返回与给定节点具有相同 label 的那个节点.
}
public ArrayList getNodes(UndirectedGraphNode node){
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
HashSet<UndirectedGraphNode> set = new HashSet<UndirectedGraphNode>();
queue.offer(node) ;
set.add(node) ;
while(!queue.isEmpty()){
UndirectedGraphNode head = queue.poll();
for(UndirectedGraphNode neighbor : head.neighbors){
if(!set.contains(neighbor)){
queue.offer(neighbor);
set.add(neighbor) ;
}
}
}
return new ArrayList<UndirectedGraphNode>(set) ;
}
}
本文介绍了一种解决方案,如何使用Java实现无向图的深度复制,CloneGraph方法确保新图与原图结构相同,修改新图不影响原图。通过UndirectedGraphNode类,展示了节点的唯一标识和邻居列表的操作,以及如何利用哈希映射和队列来遍历和复制整个图结构。
358

被折叠的 条评论
为什么被折叠?



