-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_133_Clone_Graph.cpp
More file actions
56 lines (49 loc) · 1.22 KB
/
Copy pathLeetCode_133_Clone_Graph.cpp
File metadata and controls
56 lines (49 loc) · 1.22 KB
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
54
55
56
/*
133. Clone Graph
Given a reference of a node in a connected undirected graph, return a deep copy
(clone) of the graph. Each node in the graph contains a val (int) and a list
(List[Node]) of its neighbors.
*/
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node* cloneGraph(Node* node) {
map<Node*, Node*> oldToNewNode;
map<Node*, bool> visited;
Node *curr;
// Do BFS and create new nodes
queue<Node*> q;
q.push( node );
visited[ node ] = true;
while( !q.empty() ) {
curr = q.front();
q.pop();
oldToNewNode[ curr ] = new Node( curr->val, {} );
for( auto neighbor : curr->neighbors ) {
if( visited.find( neighbor) == visited.end() ) {
q.push( neighbor );
visited[ neighbor ] = true;
}
}
}
// set neighbors for new nodes
for( auto oldToNew : oldToNewNode ) {
for( auto neighbor : oldToNew.first->neighbors ) {
oldToNew.second->neighbors.push_back( oldToNewNode[neighbor] );
}
}
return oldToNewNode[ node ];
}
};