133. 克隆图
给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。
中等难度。使用DFS深度优先遍历即可解决。
public Node cloneGraph( Node node ){
if( node == null ){
return node;
}
//hashmap存储新旧节点的对应关系,以及用来区分已克隆和未克隆的节点
HashMap map = new HashMap<>();
//保存需要进行克隆的节点
linkedList queue = new linkedList<>();
queue.offer( node );
map.put( node, new Node( node.val ) );
while( !queue.isEmpty() ){
//取出队列头部节点
Node cur = queue.poll();
//遍历并克隆节点的neighbors
for( Node neighbor : cur.neighbors ){
//如果map不包含对应的节点则加入queue,并且克隆并存入map中
if( !map.containsKey( neighbor ) ){
queue.offer( neighbor );
map.put( neighbor, new Node( neighbor.val ) );
}
//设置克隆节点的neighbors
map.get( cur ).neighbors.add( map.get( neighbor ) );
}
}
return map.get( node );
}



