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
+ /* *
2
+ * Definition for undirected graph.
3
+ * struct UndirectedGraphNode {
4
+ * int label;
5
+ * vector<UndirectedGraphNode *> neighbors;
6
+ * UndirectedGraphNode(int x) : label(x) {};
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ UndirectedGraphNode *cloneGraph (UndirectedGraphNode *node) {
12
+ // Note: The Solution object is instantiated only once and is reused by each test case.
13
+ if (node == NULL )
14
+ return NULL ;
15
+ UndirectedGraphNode *ret = new UndirectedGraphNode (node->label );
16
+
17
+ map<UndirectedGraphNode *, UndirectedGraphNode *> mp;
18
+ mp[node] = ret;
19
+ queue<UndirectedGraphNode *> que;
20
+ que.push (node);
21
+
22
+ UndirectedGraphNode *tmp = NULL , *nxt = NULL ;
23
+ while (!que.empty ()) {
24
+ tmp = que.front ();
25
+ que.pop ();
26
+ for (int i = 0 ; i < (tmp->neighbors ).size (); i++) {
27
+ nxt = (tmp->neighbors )[i];
28
+ if (mp.find (nxt) == mp.end ()) {
29
+ mp[nxt] = new UndirectedGraphNode (nxt->label );
30
+ que.push (nxt);
31
+ }
32
+ (mp[tmp]->neighbors ).push_back (mp[nxt]);
33
+ }
34
+ }
35
+ return ret;
36
+ }
37
+ };
You can’t perform that action at this time.
0 commit comments