29ms C++ dfs solution beat 100%


  • 0
    H
    class Solution {
    public:
        unordered_map<int,UndirectedGraphNode*> vis;
        unordered_map<int,UndirectedGraphNode*>::iterator itr;
        void dfs(UndirectedGraphNode *clone, UndirectedGraphNode *now){
            for(int i=0;i<now->neighbors.size();i++)
            {
                itr = vis.find(now->neighbors[i]->label);
                if(itr==vis.end())
                {
                    UndirectedGraphNode *tmp = new UndirectedGraphNode(now->neighbors[i]->label);
                    clone->neighbors.push_back(tmp);
                    vis[now->neighbors[i]->label] = tmp;
                    dfs(tmp,now->neighbors[i]);
                }
                else
                {
                    clone->neighbors.push_back(vis[now->neighbors[i]->label]);
                }
            }
        }
        UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
            if(node == NULL)
                return NULL;
            UndirectedGraphNode *clone = new UndirectedGraphNode(node->label);
            vis[(node->label)] = clone;
            dfs(clone,node);
            return clone;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.