LeetCode 133. Clone Graph

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
static auto x = []()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}();
/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */

class Solution {
private:
    UndirectedGraphNode *cloneGraphHelper(UndirectedGraphNode *node,unordered_map<int, UndirectedGraphNode*> &m) {
        if(node==NULL)return NULL;
        unordered_map<int, UndirectedGraphNode*>::iterator it=m.find(node->label);
        if(it!=m.end()){
            return it->second;
        }
        else{
            UndirectedGraphNode* newNode=new UndirectedGraphNode(node->label);
            m[node->label]=newNode;
            for(UndirectedGraphNode *orinNeighbors:node->neighbors){
                newNode->neighbors.push_back(cloneGraphHelper(orinNeighbors,m));
            }
            return newNode;
        }
    };
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(node==NULL)return NULL;
        unordered_map<int, UndirectedGraphNode*> m;
        cloneGraphHelper(node,m);
        return m[node->label];
    };
};



10 Replies to “LeetCode 133. Clone Graph”

  1. I’m really inspired along with your writing abilities as well as with
    the structure for your blog. Is that this a paid theme or
    did you customize it yourself? Either way stay up the nice quality writing, it’s
    rare to look a nice weblog like this one today..

  2. I blog frequently annd I really thank you for yyour information. This great article has truly peaked my interest.
    I’m going tto book mark your site and keep checking for new details
    about once a week. I subscribed to your RSS feed too.

  3. Have you ever considered publishing an e-book or guest authoring on other websites?
    I have a blog based upon on the same ideas you discuss and would really like to have you share some stories/information. I know my subscribers would enjoy your work.
    If you’re even remotely interested, feel free to send me an email.

Leave a Reply

Your email address will not be published. Required fields are marked *