133. leetcode-Clone Graph

拷贝图,可以一边遍历一边拷贝

DFS

class Solution {
public:
    Node* cloneGraph(Node* node) {
        unordered_map visited;
        return DFS(node, visited);
    }
    Node* DFS(Node* node, unordered_map& m)
    {
        if(!node) return NULL;
        if(m.find(node->val) != m.end()) return m[node->val];
        
        Node* n = new Node(node->val);
        m[node->val] = n;
        vector::iterator it = node->neighbors.begin();
        while(it != node->neighbors.end())
        {
            n->neighbors.push_back(DFS(*it, m));
            it++;
        }
        return n; 
    }
};

 BFS

class Solution {
public:
    Node* cloneGraph(Node* node) {
        unordered_map<int, Node*> m;
        queue q;
        queue n;
        Node* r = new Node(node->val);
        m[r->val] = r;
        q.push(node);
        n.push(r);
        while(!q.empty() && !n.empty())
        {
            Node* p = q.front();
            q.pop();
            Node* v = n.front();
            n.pop();
            vector::iterator it = p->neighbors.begin();
            while(it != p->neighbors.end())
            {
                if(m.find((*it)->val) == m.end()) 
                {
                    Node* new_node = new Node((*it)->val);
                    v->neighbors.push_back(new_node);
                    n.push(new_node); 
                    m[(*it)->val] = new_node;
                    q.push(*it);
                }
                else{
                    v->neighbors.push_back(m[(*it)->val]);
                }
                it++;
            }
        }
        return r;
    }
};

 

你可能感兴趣的:(133. leetcode-Clone Graph)