当前位置:网站首页>133. Clone map

133. Clone map

2022-07-08 00:59:00 anieoo

Original link :133. Clone map

 

solution:

        dfs Establish the mapping from the origin to the clone point , You can traverse it once

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> neighbors;
    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }
    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }
    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
*/

class Solution {
public:
    unordered_map<Node *, Node *> hash;
    Node* cloneGraph(Node* node) {
        if(node == NULL) return node;
        dfs(node);  // Building mapping 

        for(auto [s, d] : hash) {
            for(auto ver : s->neighbors) {
                d->neighbors.push_back(hash[ver]);
            }
        }
        return hash[node];
    }

    //dfs Used to realize the mapping from the original point to the clone point 
    void dfs(Node *root) {
        hash[root] = new Node(root->val);
        for(auto ver : root->neighbors) {
            if(hash[ver] == 0)
                dfs(ver);
        }
    }
};
原网站

版权声明
本文为[anieoo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/189/202207072317564179.html