forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
133.cpp
78 lines (63 loc) · 1.92 KB
/
133.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>
#include <map>
using namespace std;
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
class Solution {
map<UndirectedGraphNode *, UndirectedGraphNode *> copyMap;
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL) return NULL;
return dfs(node);
}
UndirectedGraphNode* dfs(UndirectedGraphNode *node) {
UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);
copyMap[node] = new_node;
for (auto u : node->neighbors) {
if (copyMap[u]) {
new_node->neighbors.push_back(copyMap[u]);
}
else {
new_node->neighbors.push_back(dfs(u));
}
}
return new_node;
}
void printGraph(UndirectedGraphNode *node) {
map<UndirectedGraphNode *, bool> visited;
printHelper(visited, node);
printf("\n");
}
void printHelper(map<UndirectedGraphNode *, bool> &visited, UndirectedGraphNode *node) {
if (node == NULL) return;
if (visited[node]) return;
printf("%d", node->label);
for (auto u : node->neighbors) {
printf(",%d", u->label);
}
printf("#");
visited[node] = true;
for (auto u : node->neighbors) {
printHelper(visited, u);
}
}
};
int main() {
UndirectedGraphNode *zero = new UndirectedGraphNode(0);
UndirectedGraphNode *one = new UndirectedGraphNode(1);
UndirectedGraphNode *two = new UndirectedGraphNode(2);
zero->neighbors = { one, two };
one->neighbors = { two };
two->neighbors = { two };
Solution s;
printf(" Graph: ");
s.printGraph(zero);
UndirectedGraphNode *cloned = s.cloneGraph(zero);
printf("Cloend: ");
s.printGraph(cloned);
return 0;
}