forked from Dungeonlx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclonegraph.cpp
110 lines (90 loc) · 2.37 KB
/
clonegraph.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Copyright (C) 2013 Leslie Zhai <xiangzhai83@gmail.com>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
template<typename T> class graph_node;
typedef graph_node<int> Node;
typedef std::unordered_map<Node*, Node*> Map;
typedef std::unordered_map<Node*, Node*>::iterator MapIter;
template<typename T> class graph_node
{
public:
graph_node() {}
graph_node(T data) :m_data(data) {}
~graph_node() {}
public:
std::vector<graph_node<T>*> neighbors;
T get_data() { return m_data; }
private:
T m_data;
};
static Node* graphCopy = NULL;
static Map map;
static void m_cleanup()
{
MapIter iter;
int i;
for (iter = map.begin(); iter != map.end(); iter++)
{
for (i = 0; i < (*iter).second->neighbors.size(); i++)
{
delete (*iter).second->neighbors[i];
(*iter).second->neighbors[i] = NULL;
}
}
if (graphCopy)
{
delete graphCopy;
graphCopy = NULL;
}
}
Node* clone(Node* graph)
{
if (!graph)
return NULL;
else
std::cout << "DEBUG: origin graph node " << graph->get_data() << std::endl;
std::queue<Node*> q;
q.push(graph);
graphCopy = new Node();
map[graph] = graphCopy;
while (!q.empty())
{
Node* node = q.front();
q.pop();
int n = node->neighbors.size();
for (int i = 0; i < n; i++)
{
Node* neighbor = node->neighbors[i];
std::cout << "DEBUG: neighbor " << neighbor->get_data() << std::endl;
// 没有该副本
if (map.find(neighbor) == map.end())
{
Node* p = new Node();
std::cout << "DEBUG: new clone" << std::endl;
map[node]->neighbors.push_back(p);
map[neighbor] = p;
q.push(neighbor);
}
else
{
// 副本已经存在
std::cout << "DEBUG: cloned exist " << map[neighbor]->get_data() << std::endl;
map[node]->neighbors.push_back(map[neighbor]);
}
}
}
return graphCopy;
}
int main(int argc, char* argv[])
{
Node* n1 = new Node(1);
Node* n2 = new Node(2);
Node* n3 = new Node(3);
n1->neighbors.push_back(n2);
n1->neighbors.push_back(n3);
clone(n1);
m_cleanup();
return 0;
}