首页 > 代码库 > LeetCode "Clone Graph"
LeetCode "Clone Graph"
A BFS usage.
class Solution {public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if (!node) return NULL; UndirectedGraphNode *pRet = NULL; queue<UndirectedGraphNode*> q; unordered_map<int, UndirectedGraphNode *> map; q.push(node); while (!q.empty()) { UndirectedGraphNode *p = q.front(); // Create new node UndirectedGraphNode *pNew = NULL; if (map.find(p->label) == map.end()) { pNew = new UndirectedGraphNode(p->label); map[p->label] = pNew; if (!pRet) pRet = pNew; } else { pNew = map[p->label]; } for (UndirectedGraphNode *pC : p->neighbors) { UndirectedGraphNode *pNewC = NULL; if (map.find(pC->label) == map.end()) { pNewC = new UndirectedGraphNode(pC->label); map[pC->label] = pNewC; q.push(pC); } else { pNewC = map[pC->label]; } pNew->neighbors.push_back(pNewC); } q.pop(); } return pRet; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。