forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path133.Clone Graph_BFS.cpp
42 lines (39 loc) · 1.25 KB
/
133.Clone Graph_BFS.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
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node)
{
if (node==NULL) return NULL;
unordered_map<UndirectedGraphNode*,UndirectedGraphNode*>Map;
queue<UndirectedGraphNode*>q;
q.push(node);
Map[node] = new UndirectedGraphNode(node->label);
while (!q.empty())
{
UndirectedGraphNode* root = q.front();
q.pop();
for (int i=0; i<root->neighbors.size(); i++)
{
if (Map.find(root->neighbors[i])==Map.end())
{
UndirectedGraphNode* temp = new UndirectedGraphNode(root->neighbors[i]->label);
Map[root->neighbors[i]] = temp;
Map[root]->neighbors.push_back(temp);
q.push(root->neighbors[i]);
}
else
{
Map[root]->neighbors.push_back(Map[root->neighbors[i]]);
}
}
}
return Map[node];
}
};