-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path133.Clone_Graph.cpp
More file actions
50 lines (39 loc) · 1.16 KB
/
133.Clone_Graph.cpp
File metadata and controls
50 lines (39 loc) · 1.16 KB
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
#include <vector>
#include <map>
#include <cstdlib>
using namespace std;
//Definition for undirected graph.
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
class Solution {
private:
map<int, UndirectedGraphNode *> newNodes;
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
//Deal with empty graph
if (node == NULL) {
return NULL;
}
//if the node is alread in new Nodes, just return
if (newNodes.find(node->label) != newNodes.end()) {
return newNodes[node->label];
}
//Clone the Node
UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);
newNodes[new_node->label] = new_node;
//Clone all its neighbors
for(vector<UndirectedGraphNode *>::iterator iterator = node->neighbors.begin();
iterator != node->neighbors.end();
iterator++) {
new_node->neighbors.push_back(cloneGraph(*iterator));
}
//return
return new_node;
}
};
int main(int argc, char **argv) {
return 0;
}