-
Notifications
You must be signed in to change notification settings - Fork 288
/
Copy pathAC_dfs_n.cpp
57 lines (46 loc) · 1.27 KB
/
AC_dfs_n.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
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_dfs_n.cpp
* Create Date: 2015-01-21 09:44:46
* Descripton: dfs
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
// Definition for undirected graph.
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
typedef unordered_map<int, UndirectedGraphNode *> immap;
class Solution {
private:
immap gmap;
UndirectedGraphNode *dfs(UndirectedGraphNode *node) {
UndirectedGraphNode *newnode;
if (gmap.find(node->label) == gmap.end()) {
newnode = new UndirectedGraphNode(node->label);
gmap.insert(immap::value_type(node->label, newnode));
for (auto &i : node->neighbors)
newnode->neighbors.push_back(dfs(i));
} else {
newnode = gmap[node->label];
}
return newnode;
}
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (!node)
return NULL;
gmap.clear();
UndirectedGraphNode *ret = dfs(node);
return ret;
}
};
int main() {
Solution s;
UndirectedGraphNode *a = new UndirectedGraphNode(0), *b;
b = s.cloneGraph(a);
return 0;
}