133-Clone Graph
//给无向连通图中一个节点的引用,返回该图的深拷贝
public class solution133{
class Node{
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
public Node cloneGraph(Node node) {
Node node1=new Node(node.val);
node1.neighbors=node.neighbors;
for(Node no:node1.neighbors) {
//这里不知道怎么写
}
return node1;
}
public Node cloneGraph01(Node node) {
Node node1=new Node(node.val);
node1.neighbors=node.neighbors;
//迭代,每次复制完本身,就去迭代复制它的neighbors
for(Node no:node1.neighbors) {
}
return node1;
}
}
//方法1,DFS,加入map为了看是不是加过这个。
public Node cloneGraph1(Node node) {return dfs(node,new HashMap<>());}
private Node dfs(Node node, HashMap<Integer,Node> map) {
if(node==null)return null;
if(map.containsKey(node.val)) {//有就不加进去
return map.get(node.val);
}
Node newNode=new Node(node.val,new ArrayList<>());
map.put(node.val, newNode);
for(Node neighbor:node.neighbors) {
newNode.neighbors.add(dfs(neighbor,map));//从已有的数据里找neighbors加上
}
return newNode;
}