当前位置:网站首页>133. 克隆图

133. 克隆图

2022-07-07 23:18:00 anieoo

原题链接:133. 克隆图

 

solution:

        dfs建立原点到克隆点的映射,在遍历一遍即可

/*
// 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);  //建立映射

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

    //dfs用来实现原来的点到克隆点的映射
    void dfs(Node *root) {
        hash[root] = new Node(root->val);
        for(auto ver : root->neighbors) {
            if(hash[ver] == 0)
                dfs(ver);
        }
    }
};
原网站

版权声明
本文为[anieoo]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_42174306/article/details/125667751