forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
51 lines (38 loc) · 1.16 KB
/
main3.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
/// Source : https://leetcode.com/problems/clone-graph/description/
/// Author : liuyubobobo
/// Time : 2018-09-14
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/// Definition for undirected graph.
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
/// DFS
/// Time Complexity: O(V+E)
/// Space Complexity: O(V)
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL)
return NULL;
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> nodeMap;
return dfs(node, nodeMap);
}
private:
UndirectedGraphNode *dfs(UndirectedGraphNode *node,
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*>& nodeMap){
if(nodeMap.count(node))
return nodeMap[node];
nodeMap[node] = new UndirectedGraphNode(node->label);
for(UndirectedGraphNode* next: node->neighbors)
nodeMap[node]->neighbors.push_back(dfs(next, nodeMap));
return nodeMap[node];
}
};
int main() {
return 0;
}