题目:
Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
题解:
按BFS遍历 Old Graph,创建Map保存Old Graph到New Graph的节点的映射,每当从队列中弹出一个元素并处理其neighbor时,先在map中寻找是否已存在该邻居节点从老节点到新节点的映射,如果不存在,创建新节点,并将新节点加入new graph当前节点的邻居列表中,如果存在,直接从map中读出该节点并加入到当前节点的邻居列表中。
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if(!node) return node; queue<UndirectedGraphNode*> nodeQueue; map<UndirectedGraphNode*, UndirectedGraphNode*> visited; UndirectedGraphNode *newRoot = new UndirectedGraphNode(node->label); visited[node] = newRoot; nodeQueue.push(node); while(!nodeQueue.empty()) { UndirectedGraphNode *old = nodeQueue.front(); nodeQueue.pop(); for(auto iter: old->neighbors) { if(!visited.count(iter)) { UndirectedGraphNode *newNode = new UndirectedGraphNode(iter->label); visited[old]->neighbors.push_back(newNode); visited[iter] = newNode; nodeQueue.push(iter); } else { visited[old]->neighbors.push_back(visited[iter]); } } } return newRoot; } };