-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclone_graph.cpp
85 lines (73 loc) · 2.82 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <queue>
#include <vector>
#include <map>
#include <map>
using namespace std;
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
typedef vector<UndirectedGraphNode *>::iterator vi;
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (!node)
return NULL;
UndirectedGraphNode *ch = new UndirectedGraphNode(node->label);
pair<UndirectedGraphNode *, UndirectedGraphNode *> np(node, ch);
map<UndirectedGraphNode *, UndirectedGraphNode *> set;
set.insert(np);
queue<pair<UndirectedGraphNode *, UndirectedGraphNode *>> q;
q.push(np);
while (!q.empty()) {
pair<UndirectedGraphNode *, UndirectedGraphNode *> t = q.front();q.pop();
for (vi i = t.first->neighbors.begin(); i != t.first->neighbors.end(); i++) {
if (set.find(*i) == set.end()) {
UndirectedGraphNode *tmp = new UndirectedGraphNode((*i)->label);
pair<UndirectedGraphNode *, UndirectedGraphNode *> tp = pair<UndirectedGraphNode *, UndirectedGraphNode *>(*i, tmp);
set.insert(tp);
t.second->neighbors.push_back(tmp);
q.push(pair<UndirectedGraphNode *, UndirectedGraphNode *>(tp));
} else {
t.second->neighbors.push_back(set[*i]);
}
}
}
return ch;
}
};
void print(UndirectedGraphNode *n)
{
if (!n)
return;
if (n->label != -1)
cout << n->label << " ";
else
return;
n->label = -1;
for (vi i = n->neighbors.begin(); i != n->neighbors.end(); i++) {
print(*i);
}
}
int main()
{
/*
UndirectedGraphNode *n0 = new UndirectedGraphNode(0);
UndirectedGraphNode *n1 = new UndirectedGraphNode(1);
UndirectedGraphNode *n2 = new UndirectedGraphNode(2);
UndirectedGraphNode *n3 = new UndirectedGraphNode(3);
UndirectedGraphNode *n4 = new UndirectedGraphNode(4);
n0->neighbors.push_back(n1);
n0->neighbors.push_back(n2);
n1->neighbors.push_back(n3);
n2->neighbors.push_back(n4);
n4->neighbors.push_back(n4);
*/
UndirectedGraphNode *n0 = new UndirectedGraphNode(0);
Solution s;
UndirectedGraphNode *ne = s.cloneGraph(n0);
print(ne);
return 0;
}