Skip to content

Commit 82e9776

Browse files
authoredNov 15, 2022
Merge pull request #1467 from elcabalero/patch-3
Updated clone_graph as in the video
2 parents 3cfb9a5 + 2ad1917 commit 82e9776

File tree

1 file changed

+50
-29
lines changed

1 file changed

+50
-29
lines changed
 

‎cpp/neetcode_150/11_graphs/clone_graph.cpp

+50-29
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
/*
22
Given ref of a node in connected undirected graph, return deep copy
3-
43
Both BFS & DFS work, map original node to its copy
5-
64
Time: O(m + n)
75
Space: O(n)
86
*/
@@ -47,37 +45,60 @@ class Node {
4745
// unordered_map<Node*, Node*> m;
4846
// };
4947

48+
// class Solution {
49+
// public:
50+
// Node* cloneGraph(Node* node) {
51+
// if (node == NULL) {
52+
// return NULL;
53+
// }
54+
//
55+
// Node* copy = new Node(node->val);
56+
// m[node] = copy;
57+
//
58+
// queue<Node*> q;
59+
// q.push(node);
60+
//
61+
// while (!q.empty()) {
62+
// Node* curr = q.front();
63+
// q.pop();
64+
//
65+
// for (int i = 0; i < curr->neighbors.size(); i++) {
66+
// Node* neighbor = curr->neighbors[i];
67+
//
68+
// if (m.find(neighbor) == m.end()) {
69+
// m[neighbor] = new Node(neighbor->val);
70+
// q.push(neighbor);
71+
// }
72+
//
73+
// m[curr]->neighbors.push_back(m[neighbor]);
74+
// }
75+
// }
76+
//
77+
// return copy;
78+
// }
79+
// private:
80+
// unordered_map<Node*, Node*> m;
81+
// };
82+
5083
class Solution {
5184
public:
5285
Node* cloneGraph(Node* node) {
53-
if (node == NULL) {
54-
return NULL;
55-
}
56-
57-
Node* copy = new Node(node->val);
58-
m[node] = copy;
59-
60-
queue<Node*> q;
61-
q.push(node);
62-
63-
while (!q.empty()) {
64-
Node* curr = q.front();
65-
q.pop();
66-
67-
for (int i = 0; i < curr->neighbors.size(); i++) {
68-
Node* neighbor = curr->neighbors[i];
69-
70-
if (m.find(neighbor) == m.end()) {
71-
m[neighbor] = new Node(neighbor->val);
72-
q.push(neighbor);
73-
}
74-
75-
m[curr]->neighbors.push_back(m[neighbor]);
76-
}
77-
}
78-
79-
return copy;
86+
if (node == nullptr)
87+
return nullptr;
88+
return dfs(node);
8089
}
8190
private:
8291
unordered_map<Node*, Node*> m;
92+
93+
Node* dfs(Node* node){
94+
if (m.find(node) != m.end())
95+
return m[node];
96+
97+
Node* n = new Node(node->val);
98+
m[node] = n;
99+
for (Node* neigh : node->neighbors){
100+
n->neighbors.push_back(dfs(neigh));
101+
}
102+
return n;
103+
}
83104
};

0 commit comments

Comments
 (0)