forked from fuellee/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clone_Graph.cpp
53 lines (46 loc) · 1.31 KB
/
Clone_Graph.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
/*
* Clone_Graph.cpp
* Copyright (C) 2014 fuel <fuel@fuel-3330>
*
* Distributed under terms of the MIT license.
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
class Solution {
typedef UndirectedGraphNode N;
unordered_map<N*,N*> old2new;
queue<N*> Q;
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *graph) {
if(graph==nullptr) return nullptr;
Q.push(graph);
old2new[graph]=new N(graph->label);
while(!Q.empty()) {
auto curN = Q.front(); Q.pop();
auto &neighbors = curN->neighbors;
auto &NewNeighors = old2new[curN]->neighbors;
for(auto &neighbor: neighbors) {
if(old2new.find(neighbor)==old2new.end()) {
auto NewNeighor = new N(neighbor->label);
old2new[neighbor]=NewNeighor;
NewNeighors.push_back(NewNeighor);
Q.push(neighbor);
}
else
NewNeighors.push_back(old2new[neighbor]);
}
}
return old2new[graph];
}
};
int main() {
return 0;
}