克隆一个图结构。
1 struct Node{ 2 vector<Node*> neighbors; 3 };
代码如下:
1 typedef unordered_map<Node*, Node*> Map; 2 3 Node* cloneGraph(Node* graph) 4 { 5 if (!graph) 6 return NULL; 7 8 Map map; 9 Node* graphCopy = new Node(); 10 map[graph] = graphCopy; 11 12 queue<Node*> q; 13 q.push(graph); 14 while (!q.empty()) { 15 Node* node = q.front(); 16 q.pop(); 17 int n = node->neighbors.size(); 18 for (int i = 0; i < n; i++) { 19 Node* neighbor = node->neighbors[i]; 20 if (map.find(neighbor) == map.end()) { 21 Node* copy = new Node(); 22 map[neighbor] = copy; 23 map[node]->neighbors.push_back(copy); 24 q.push(neighbor); 25 } else { 26 map[node]->neighbors.push_back(map[neighbor]); 27 } 28 } 29 return graphCopy; 30 }
时间: 2024-10-05 04:58:38