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
|
void dfs(UndirectedGraphNode* node, unordered_map<int, UndirectedGraphNode*>& copy) { copy[node->label] = new UndirectedGraphNode(node->label); for(auto v : node->neighbors) { if(copy.count(v->label)) continue; dfs(v, copy); } } void dfs2(UndirectedGraphNode* node, unordered_map<int, UndirectedGraphNode*>& copy, unordered_set<int>& vis) { vis.insert(node->label); for(auto v : node->neighbors) { copy[node->label]->neighbors.push_back(copy[v->label]); if(!vis.count(v->label)) dfs2(v, copy, vis); } } UndirectedGraphNode *Solution::cloneGraph(UndirectedGraphNode *node) { unordered_map<int, UndirectedGraphNode*> copy; dfs(node, copy); dfs2(node, copy, unordered_set<int>() = {}); return copy[node->label]; }
|