码迷,mamicode.com
首页 > 其他好文 > 详细

133. Clone Graph

时间:2018-05-20 16:47:26      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:return   cte   clone   for   rap   nod   pre   label   dfs   

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    unordered_map<UndirectedGraphNode *,UndirectedGraphNode *> m;
    unordered_set<UndirectedGraphNode *> visited;
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (node == NULL)   return NULL;
        dfs_create(node);
        dfs_link(node);
        return m[node];
    }
    void dfs_create(UndirectedGraphNode *node) {
        if (node == NULL || m.count(node))   return;
        UndirectedGraphNode *p = new UndirectedGraphNode(node->label);
        m[node] = p;
        for (auto n : node->neighbors)
            dfs_create(n);
    }
    void dfs_link(UndirectedGraphNode *node) {
        if (node == NULL || visited.count(node))   return;
        visited.insert(node);
        for (auto n : node->neighbors) {
            m[node]->neighbors.push_back(m[n]);
            dfs_link(n);
        }
    }
};

 

133. Clone Graph

标签:return   cte   clone   for   rap   nod   pre   label   dfs   

原文地址:https://www.cnblogs.com/JTechRoad/p/9063544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!