LeetCode133.克隆圖
阿新 • • 發佈:2018-11-11
可以使用DFS和BFS。參考https://blog.csdn.net/qq508618087/article/details/50806972
1.DFS 判斷當前節點是否被建立,如果建立直接返回。使用unordered_map來儲存已經建立的節點。遞迴訪問每個節點和每個鄰居
class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if (!node) return NULL; if (hash.count(node)) return hash[node];//當前unorder_map中已經存在直接反回 hash[node] = new UndirectedGraphNode(node->label); for (auto val : node->neighbors) hash[node]->neighbors.push_back(cloneGraph(val)); return hash[node]; } private: unordered_map<UndirectedGraphNode *, UndirectedGraphNode *>hash; };
2.BFS 使用佇列來儲存已經構建好的節點。首先將起始節點放入佇列,然後進行廣度遍歷,遍歷的物件為當前節點的鄰居節點,如果還沒被建立,則建立並放入佇列。最後將會遍歷所有節點完成克隆。
class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if (!node) return NULL; UndirectedGraphNode* graph = new UndirectedGraphNode(node->label); hash[node] = graph; queue<UndirectedGraphNode*> q; q.push(node); while (!q.empty()) { auto curNode = q.front(); q.pop(); for (auto val : curNode->neighbors) { if (hash.find(val) == hash.end()) { hash[val] = new UndirectedGraphNode(val->label); q.push(val); } hash[curNode]->neighbors.push_back(hash[val]); } } return graph; } private: unordered_map<UndirectedGraphNode *, UndirectedGraphNode *>hash; };