forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclone-graph(AC).cpp
More file actions
66 lines (61 loc) · 1.48 KB
/
clone-graph(AC).cpp
File metadata and controls
66 lines (61 loc) · 1.48 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Mapping and recursion
#include <unordered_map>
using namespace std;
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
typedef UndirectedGraphNode UGN;
class Solution {
public:
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
UGN *cloneGraph(UGN *node) {
if (node == NULL) {
return NULL;
}
n = 0;
um.clear();
b.clear();
v.clear();
um[node] = n++;
v.push_back(new UGN(node->label));
b.push_back(false);
DFS(node);
return v[0];
}
private:
int n;
unordered_map<UGN *, int> um;
vector<bool> b;
vector<UGN *> v;
void DFS(UGN *node) {
if (b[um[node]]) {
return;
}
b[um[node]] = true;
UGN *newNode = v[um[node]];
int nn = node->neighbors.size();
int i;
UGN *p;
for (i = 0; i < nn; ++i) {
p = node->neighbors[i];
if (um.find(p) == um.end()) {
um[p] = n++;
b.push_back(false);
v.push_back(new UGN(p->label));
}
newNode->neighbors.push_back(v[um[p]]);
}
for (i = 0; i < nn; ++i) {
p = node->neighbors[i];
DFS(p);
}
}
};