forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.h
28 lines (26 loc) · 785 Bytes
/
solution.h
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
#include <vector>
using std::vector;
#include <unordered_map>
using std::unordered_map;
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
class Solution {
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> map;
void dfs(UndirectedGraphNode *node) {
if (map.find(node) != map.end()) return;
map[node] = new UndirectedGraphNode(node->label);
for (UndirectedGraphNode *neighbor : node->neighbors) {
dfs(neighbor);
map[node]->neighbors.push_back(map[neighbor]);
}
}
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (!node) return node;
dfs(node);
return map[node];
}
};