Skip to content

Commit 6321305

Browse files
committedOct 15, 2015
"Clone Graph"
1 parent 6d31949 commit 6321305

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed
 

‎README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
167167
| 136 | [Single Number] | [C](src/136.c) |
168168
| 135 | [Candy] | |
169169
| 134 | [Gas Station] | |
170-
| 133 | [Clone Graph] | |
170+
| 133 | [Clone Graph] | [C++](src/133.cpp) |
171171
| 132 | [Palindrome Partitioning II] | |
172172
| 131 | [Palindrome Partitioning] | |
173173
| 130 | [Surrounded Regions] | |

‎src/133.cpp

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <map>
4+
5+
using namespace std;
6+
7+
struct UndirectedGraphNode {
8+
int label;
9+
vector<UndirectedGraphNode *> neighbors;
10+
UndirectedGraphNode(int x) : label(x) {};
11+
};
12+
13+
class Solution {
14+
map<UndirectedGraphNode *, UndirectedGraphNode *> copyMap;
15+
public:
16+
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
17+
if (node == NULL) return NULL;
18+
return dfs(node);
19+
}
20+
21+
UndirectedGraphNode* dfs(UndirectedGraphNode *node) {
22+
UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);
23+
copyMap[node] = new_node;
24+
for (auto u : node->neighbors) {
25+
if (copyMap[u]) {
26+
new_node->neighbors.push_back(copyMap[u]);
27+
}
28+
else {
29+
new_node->neighbors.push_back(dfs(u));
30+
}
31+
}
32+
return new_node;
33+
}
34+
35+
void printGraph(UndirectedGraphNode *node) {
36+
map<UndirectedGraphNode *, bool> visited;
37+
printHelper(visited, node);
38+
printf("\n");
39+
}
40+
41+
void printHelper(map<UndirectedGraphNode *, bool> &visited, UndirectedGraphNode *node) {
42+
if (node == NULL) return;
43+
if (visited[node]) return;
44+
45+
printf("%d", node->label);
46+
for (auto u : node->neighbors) {
47+
printf(",%d", u->label);
48+
}
49+
printf("#");
50+
visited[node] = true;
51+
52+
for (auto u : node->neighbors) {
53+
printHelper(visited, u);
54+
}
55+
}
56+
};
57+
58+
int main() {
59+
60+
UndirectedGraphNode *zero = new UndirectedGraphNode(0);
61+
UndirectedGraphNode *one = new UndirectedGraphNode(1);
62+
UndirectedGraphNode *two = new UndirectedGraphNode(2);
63+
64+
zero->neighbors = { one, two };
65+
one->neighbors = { two };
66+
two->neighbors = { two };
67+
68+
Solution s;
69+
printf(" Graph: ");
70+
s.printGraph(zero);
71+
72+
UndirectedGraphNode *cloned = s.cloneGraph(zero);
73+
74+
printf("Cloend: ");
75+
s.printGraph(cloned);
76+
77+
return 0;
78+
}

0 commit comments

Comments
 (0)
Please sign in to comment.