-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy path09_clone_a_graph.cpp
64 lines (48 loc) · 1.45 KB
/
09_clone_a_graph.cpp
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
link: https://leetcode.com/problems/clone-graph/
video: https://youtu.be/jWf5F_shzho
*/
// ----------------------------------------------------------------------------------------------------------------------- //
/*
using DFS
*/
void dfs(Node* node, Node* prev, vector<Node*>& vis) {
// record in vis array
vis[prev->val] = prev;
for (auto curr : node->neighbors) {
// if not visited
if (vis[curr->val] == NULL) {
// make new node
Node* newNode = new Node(curr->val);
// save in neighbour of prev
(prev->neighbors).push_back(newNode);
// do dfs in both
dfs(curr, newNode, vis);
}
else {
// visited then push the address of visited in prev's neighbors
(prev->neighbors).push_back(vis[curr->val]);
}
}
}
Node* cloneGraph(Node* node) {
if (!node) return NULL;
vector<Node*> vis(1000, NULL);
Node* newNode = new Node(node->val);
dfs(node, newNode, vis);
return newNode;
}
// ----------------------------------------------------------------------------------------------------------------------- //
/*
using map
*/
unordered_map<Node*, Node*> mp;
Node* cloneGraph(Node* node) {
if (node && !mp[node]) {
mp[node] = new Node(node->val);
for (auto i : node->neighbors) {
mp[node]->neighbors.push_back(cloneGraph(i));
}
}
return mp[node];
}