File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(n)
3
+
4
+ /* *
5
+ * Definition for undirected graph.
6
+ * struct UndirectedGraphNode {
7
+ * int label;
8
+ * vector<UndirectedGraphNode *> neighbors;
9
+ * UndirectedGraphNode(int x) : label(x) {};
10
+ * };
11
+ */
12
+ class Solution {
13
+ public:
14
+ UndirectedGraphNode *cloneGraph (UndirectedGraphNode *node) {
15
+ if (!node)
16
+ return nullptr ;
17
+ unordered_map<const UndirectedGraphNode *, UndirectedGraphNode *> copied;
18
+ copied[node] = new UndirectedGraphNode (node->label );
19
+ queue<const UndirectedGraphNode *> q;
20
+ q.push (node);
21
+ while (!q.empty ()) {
22
+ auto node = q.front ();
23
+ q.pop ();
24
+
25
+ for (auto n : node->neighbors ) {
26
+ if (copied.find (n) == copied.end ()) {
27
+ copied[n] = new UndirectedGraphNode (n->label );
28
+ q.push (n);
29
+ }
30
+
31
+ copied[node]->neighbors .push_back (copied[n]);
32
+ }
33
+ }
34
+
35
+ return copied[node];
36
+ }
37
+ };
You can’t perform that action at this time.
0 commit comments