LeetCode 133. Clone Graph

deep copy of a graph.
注意 所谓的deep copy,就是对每一个节点 进行 new Node(node.val, List neighbor)的复制
clearly, use BFS: queue and visited

因为我们需要复制 而本来 我们只需要visited是hashset就行 就是BFS的便利的时候边加便检查就行。
但是我们现在需要deep copy,所以我们用hashmap来 采用oldnode,newnode键值对的方式。

class Solution {
    //private HashMap<Node, Node> visited = new HashMap<>();
    public Node cloneGraph(Node node) {
        if (node == null) return null;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(node);
        HashMap<Node, Node> visited = new HashMap<>(); //visited can be a hashset, but since we have to make a deep copy of that, so visited is old node-new node
        visited.put(node, new Node(node.val, new ArrayList<>()));
        
        while (!queue.isEmpty()) {
            Node cur = queue.poll();
            for (Node neigh: cur.neighbors) {
                if (!visited.containsKey(neigh)) {
                    visited.put(neigh, new Node(neigh.val, new ArrayList<>()));
                    queue.offer(neigh);//only when we haven't visited it, then we will offer it to the queue
                }
                visited.get(cur).neighbors.add(visited.get(neigh)); //the neighbr of cur needs to add the currrent this neighbor, but since all of them needs to be new node, so we retrive new node
            }
        }
        return visited.get(node);
    }
}
posted @ 2020-11-29 12:24  EvanMeetTheWorld  阅读(18)  评论(0)    收藏  举报