-
Notifications
You must be signed in to change notification settings - Fork 1
/
133.cpp
47 lines (42 loc) · 1.33 KB
/
133.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
// 133. Clone Graph - https://leetcode.com/problems/clone-graph
#include "bits/stdc++.h"
using namespace std;
// Definition for undirected graph.
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
class Solution {
private:
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> hashtable;
unordered_set<UndirectedGraphNode*> visited;
public:
void cloneNodeIf404(UndirectedGraphNode* node) {
if (!hashtable.count(node)) {
hashtable[node] = new UndirectedGraphNode(node->label);
}
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == nullptr) { return nullptr; }
queue<UndirectedGraphNode*> q;
q.push(node);
visited.insert(node);
while(!q.empty()) {
auto cur = q.front(); q.pop();
cloneNodeIf404(cur);
for (auto neighbour : cur->neighbors) {
cloneNodeIf404(neighbour);
hashtable[cur]->neighbors.emplace_back(hashtable[neighbour]);
if (visited.count(neighbour)) { continue; }
visited.insert(neighbour);
q.push(neighbour);
}
}
return hashtable[node];
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}