Skip to content

Commit 7125ebd

Browse files
committed
Clone Graph Solution
1 parent ff4c1aa commit 7125ebd

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

clone-graph/PDKhan.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public:
3+
void dfs(Node* node, unordered_map<Node*, Node*>& map){
4+
if(map.count(node))
5+
return;
6+
7+
map[node] = new Node(node->val);
8+
9+
for(int i = 0; i < node->neighbors.size(); i++)
10+
dfs(node->neighbors[i], map);
11+
}
12+
13+
Node* cloneGraph(Node* node) {
14+
if(node == NULL)
15+
return NULL;
16+
17+
unordered_map<Node*, Node*> map;
18+
19+
dfs(node, map);
20+
21+
for(auto& x : map){
22+
Node* org = x.first;
23+
Node* dst = x.second;
24+
for(int i = 0; i < org->neighbors.size(); i++){
25+
dst->neighbors.push_back(map[org->neighbors[i]]);
26+
}
27+
}
28+
29+
return map[node];
30+
}
31+
};

0 commit comments

Comments
 (0)