標籤:
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 class Solution {10 public:11 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {12 if (!node) return NULL;13 unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> mapping;14 UndirectedGraphNode *result = new UndirectedGraphNode(node->label);15 queue<UndirectedGraphNode *> q;16 mapping[node] = result;17 q.push(node);18 while (!q.empty()) {19 UndirectedGraphNode *current = q.front();20 q.pop();21 for (int i = 0; i < current->neighbors.size(); i++) {22 if (mapping.find(current->neighbors[i]) == mapping.end()) {23 UndirectedGraphNode *newNode = new UndirectedGraphNode(current->neighbors[i]->label);24 q.push(current->neighbors[i]);25 mapping[current->neighbors[i]] = newNode;26 mapping[current]->neighbors.push_back(newNode);27 } else {28 mapping[current]->neighbors.push_back(mapping[current->neighbors[i]]);29 }30 }31 }32 return result;33 }34 };
LeetCode – Refresh – Clone Graph