133.克隆图
本题就是遍历整个图,遍历的时候要记录已经访问过的节点
方法一:深度优先搜索
/*
// Definition for a Node.
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;}
}
*/class Solution {HashMap<Node,Node> visited = new HashMap<>();public Node cloneGraph(Node node) {if(node == null){return node;}//如果该节点已经被访问过,则直接从哈希表中取出对应的克隆节点返回if(visited.containsKey(node)){return visited.get(node);}//克隆节点,注意到为了深拷贝不会克隆他的邻居列表Node cloneNode = new Node(node.val,new ArrayList());//哈希表存储visited.put(node,cloneNode);//遍历该节点的邻居并更新克隆节点的邻居列表for(Node neighbor : node.neighbors){cloneNode.neighbors.add(cloneGraph(neighbor));}return cloneNode;}
}
方法二:广度优先搜索
/*
// Definition for a Node.
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;}
}
*/class Solution {public Node cloneGraph(Node node) {if(node == null){return node;}HashMap<Node,Node> visited = new HashMap<>();//将给定的节点添加到队列LinkedList<Node> queue = new LinkedList<Node>();queue.add(node);//克隆第一个节点并存储到哈希表中visited.put(node,new Node(node.val,new ArrayList()));//广度优先搜索while(!queue.isEmpty()){//取出队列的头结点Node n = queue.remove();//遍历该节点的邻居for(Node neighbor : n.neighbors){if(!visited.containsKey(neighbor)){//如果没有被访问,就克隆并存储到哈希表visited.put(neighbor,new Node(neighbor.val,new ArrayList()));//将邻居节点添加到队列中queue.add(neighbor);}//更新当前节点的邻居列表visited.get(n).neighbors.add(visited.get(neighbor));}}return visited.get(node);}
}