240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 17 | Leetcode 133. Clone Graph

题解

Medium

BFS

Deep Copy 的一个例子。

class Solution {
public:
    Node* cloneGraph(Node* node) {
        if(!node) return nullptr;
        
        unordered_map<Node*, Node*> m;
        
        Node* copy = new Node(node->val);
        
        m[node] = copy;
        
        queue<Node*> q;
        q.push(node);
        
        while(!q.empty()) {
            Node* t = q.front();
            q.pop();
            
            for(auto n : t->neighbors) {
                if(!m.count(n)) {
                    m[n] = new Node(n->val);
                    q.push(n);
                }

                m[t]->neighbors.push_back(m[n]);
            }

        }
        
        return copy;
    }
};
posted @ 2020-10-02 13:22  CasperWin  阅读(65)  评论(0编辑  收藏  举报