forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
53 lines (44 loc) · 1.36 KB
/
main2.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
/// Source : https://leetcode.com/problems/clone-graph/description/
/// Author : liuyubobobo
/// Time : 2018-09-14
#include <iostream>
#include <stack>
#include <vector>
#include <unordered_map>
using namespace std;
/// Definition for undirected graph.
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
/// Using Only One Stacks and HashMap from Node to Node
/// Time Complexity: O(V+E)
/// Space Complexity: O(V)
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL)
return NULL;
UndirectedGraphNode* ret = new UndirectedGraphNode(node->label);
stack<UndirectedGraphNode*> stack;
stack.push(node);
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> nodeMap;
nodeMap[node] = ret;
while(!stack.empty()){
UndirectedGraphNode* cur = stack.top();
stack.pop();
for(UndirectedGraphNode *next: cur->neighbors) {
if (!nodeMap.count(next)) {
nodeMap[next] = new UndirectedGraphNode(next->label);
stack.push(next);
}
nodeMap[cur]->neighbors.push_back(nodeMap[next]);
}
}
return ret;
}
};
int main() {
return 0;
}