-
Notifications
You must be signed in to change notification settings - Fork 3
/
clone_graph.cpp
66 lines (63 loc) · 1.76 KB
/
clone_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
65
66
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
// write your code here
if(node == NULL)
{
return NULL;
}
int start = 0;
//UndirectedGraphNode * nodes;
vector<UndirectedGraphNode *> list;
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> hashmap;
list.push_back(node);
hashmap[node] = new UndirectedGraphNode(node->label);
// clone nodes
while(start < list.size())
{
vector<UndirectedGraphNode *> neighbor = list[start++]->neighbors;
for(vector<UndirectedGraphNode *>::iterator it = neighbor.begin();
it != neighbor.end();
it++)
{
if(hashmap.find(*it) != hashmap.end())
{
// alreay exists. ignore
continue;
}
list.push_back(*it);
//hashmap[*it] = new UndirectedGraphNode((*it)->label);
UndirectedGraphNode * k = *it;
UndirectedGraphNode * v = new UndirectedGraphNode(k->label);
hashmap.insert(std::make_pair<UndirectedGraphNode *, UndirectedGraphNode *> (k,v));
}
}
//clone neighbors
start = 0;
while(start < list.size())
{
vector<UndirectedGraphNode *> neighbor = list[start]->neighbors;
UndirectedGraphNode * nodes = hashmap[list[start]];
for(vector<UndirectedGraphNode *>::iterator it = neighbor.begin();
it != neighbor.end();
it++)
{
nodes->neighbors.push_back(hashmap[(*it)]);
}
start++;
}
return hashmap[(node)];
}
};