# 问题描述

Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.

# 思路

1. node->nodes 使用dfs遍历图得到所有结点
2. copy nodes 用hash存储<原来结点,新结点>键值对
3. copy edges 拷贝边（邻居关系）
4. 返回新构造图的node对应的新node

# java实现

/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;

public Node() {}

public Node(int _val,List<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public Node cloneGraph(Node node) {
if(node==null)
return node;

// step 1 node->nodes 使用dfs遍历图得到所有结点
ArrayList<Node> nodes=getNodes(node);
// step 2 copy nodes 用hash存储<原来结点,新结点>键值对
HashMap<Node,Node> mapping=cloneNodes(nodes);
// step 3 copy edges 拷贝边（邻居关系）
cloneNeighbors(nodes,mapping);
//返回新构造图的node对应的新node
return mapping.get(node);

}

// step 1 node->nodes 使用dfs遍历图得到所有结点
private ArrayList<Node>  getNodes(Node node){
HashSet<Node> set=new HashSet<>();
queue.offer(node);

while (!queue.isEmpty()){
if(set.contains(neighbor))
continue;
queue.offer(neighbor);
}
}
return new ArrayList<>(set);
}

// step 2 copy nodes 用hash存储<原来结点,新结点>键值对
private  HashMap<Node,Node> cloneNodes( ArrayList<Node> nodes){
HashMap<Node,Node> mapping=new HashMap<>();
for(Node node:nodes)
mapping.put(node,new Node(node.val));//<原来结点,新结点>
return mapping;
}

// step 3 copy edges 拷贝边（邻居关系）
private void cloneNeighbors( ArrayList<Node> nodes,HashMap<Node,Node> mapping){
for(Node node:nodes){
Node newNode=mapping.get(node);//得到原来结点node对应的新结点newNode
for(Node neighbor:node.neighbors){
Node newNeighbor=mapping.get(neighbor);//<node,neighbor> -><newNode,newNeighbor>