我寫了一個簡單的算法來克隆一個無向圖使用BFS,但似乎有一些邏輯錯誤,我不明白。有人可以看看嗎?使用BFS克隆圖(無向)
這個想法是訪問每個節點,並複製它們只有一次,複製一個節點後,檢查其鄰居是否沒有複製,排隊該鄰居;如果其鄰居已被複制,則將它們放入彼此的鄰居向量中。
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
//key -> old node, value -> the new copy
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> m;
//the queue always contains old nodes that haven't been copied
queue<UndirectedGraphNode*> q;
if(node)
q.push(node);
while(!q.empty()) {
UndirectedGraphNode* n = q.front();
q.pop();
if(m.count(n)) continue; // if the node is already copied, continue
// create the copy
m[n] = new UndirectedGraphNode(n->label);
// loop through the neighbors, if it's copied already, add the new copy to new copy's neighbor list
for(UndirectedGraphNode* oldNei : n->neighbors) {
if(m.count(oldNei)) {
UndirectedGraphNode* newNei = m[oldNei];
m[n]->neighbors.push_back(newNei);
newNei->neighbors.push_back(m[n]);
}
else// if not in the map, it's not copied/visited yet
q.push(oldNei);
}
}
return m[node];
}
這裏的節點結構:
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
這裏的OJ我與練習:https://leetcode.com/problems/clone-graph/
我同意這是更好地處理空節點邊緣的情況下的方式,但我不明白爲什麼我必須要創造新for循環內的節點副本,我認爲我的方式也應該是正確的。你能指出爲什麼我的錯? – Arch1tect
檢查編輯部分答案,爲什麼你的代碼是錯誤的。 – sudoer
對,但是輸入權是?如果A和B是鄰居,那麼我認爲A應該在B的鄰居列表中,並且B也必須在A的鄰居列表中。我的算法基於此.. – Arch1tect