1. Use BFS to search the graph.
2. Create a Hashtable to record the one to one mapping.
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 classSolution {Ten Public: OneUndirectedgraphnode *clonegraph (Undirectedgraphnode *node) { A if(!node)returnNULL; -Unordered_map<undirectedgraphnode *, Undirectedgraphnode *>mapping; -Undirectedgraphnode *result =NewUndirectedgraphnode (node->label); theQueue<undirectedgraphnode *>Q; -Mapping[node] =result; - Q.push (node); - while(!Q.empty ()) { +Undirectedgraphnode *current =Q.front (); - Q.pop (); + for(inti =0; I < current->neighbors.size (); i++) { A if(Mapping.find (current->neighbors[i]) = =Mapping.end ()) { atUndirectedgraphnode *newnode =NewUndirectedgraphnode (current->neighbors[i]->label); -Q.push (current->neighbors[i]); -Mapping[current->neighbors[i]] =NewNode; -Mapping[current]->Neighbors.push_back (newNode); -}Else { -Mapping[current]->neighbors.push_back (mapping[current->Neighbors[i]]); in } - } to } + returnresult; - } the};
Leetcode–refresh–clone Graph