-
Notifications
You must be signed in to change notification settings - Fork 0
/
200210-1.cpp
139 lines (130 loc) · 2.27 KB
/
200210-1.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// https://leetcode-cn.com/problems/clone-graph/
#include <cstdio>
#include <vector>
#include <unordered_map>
using namespace std;
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
void visit(Node* t, vector<Node*>& n)
{
if (t) {
if (n.size() < t->val) {
n.resize(t->val);
}
if (!n[t->val - 1]) {
n[t->val - 1] = t;
for (auto e : t->neighbors) {
visit(e, n);
}
}
}
}
void print(Node* t)
{
vector<Node*> n; visit(t, n);
printf("[");
for (auto e : n) {
printf("[");
if (e) {
for (int i = 0; i < e->neighbors.size(); ++i) {
printf("%s%d", (i>0?",":""), e->neighbors[i]->val);
}
}
printf("]");
}
printf("]\n");
}
void release(Node* t)
{
vector<Node*> n; visit(t, n);
for (auto e : n) delete(e);
}
class Solution {
public:
Node* cloneGraph(Node* node) {
if (!node) return NULL;
unordered_map<Node*, Node*> m;
visit(node, m);
for (auto [a, b] : m) {
for (auto e : a->neighbors) {
b->neighbors.push_back(m[e]);
}
}
return m[node];
}
private:
void visit(Node* t, unordered_map<Node*, Node*>& m) {
if (m.find(t) == m.end()) {
m[t] = new Node(t->val);
for (auto n : t->neighbors) {
visit(n, m);
}
}
}
};
int main()
{
Solution s;
{
Node* t1 = new Node(1);
Node* t2 = new Node(2);
Node* t3 = new Node(3);
Node* t4 = new Node(4);
t1->neighbors.push_back(t2);
t1->neighbors.push_back(t4);
t2->neighbors.push_back(t1);
t2->neighbors.push_back(t3);
t3->neighbors.push_back(t2);
t3->neighbors.push_back(t4);
t4->neighbors.push_back(t1);
t4->neighbors.push_back(t3);
print(t1);
Node* c = s.cloneGraph(t1);
print(c);
release(c);
release(t1);
}
{
Node* t1 = new Node(1);
print(t1);
Node* c = s.cloneGraph(t1);
print(c);
release(c);
release(t1);
}
{
Node* t1 = NULL;
print(t1);
Node* c = s.cloneGraph(t1);
print(c);
release(c);
release(t1);
}
{
Node* t1 = new Node(1);
Node* t2 = new Node(2);
t1->neighbors.push_back(t2);
t2->neighbors.push_back(t1);
print(t1);
Node* c = s.cloneGraph(t1);
print(c);
release(c);
release(t1);
}
return 0;
}