您的位置:首页 > 其它

LeetCode – Refresh – Clone Graph

2015-03-19 04:32 423 查看
1. Use BFS to search the graph.

2. Create a hashtable to record the one to one mapping.

/**
* 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 NULL;
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> mapping;
UndirectedGraphNode *result = new UndirectedGraphNode(node->label);
queue<UndirectedGraphNode *> q;
mapping[node] = result;
q.push(node);
while (!q.empty()) {
UndirectedGraphNode *current = q.front();
q.pop();
for (int i = 0; i < current->neighbors.size(); i++) {
if (mapping.find(current->neighbors[i]) == mapping.end()) {
UndirectedGraphNode *newNode = new UndirectedGraphNode(current->neighbors[i]->label);
q.push(current->neighbors[i]);
mapping[current->neighbors[i]] = newNode;
mapping[current]->neighbors.push_back(newNode);
} else {
mapping[current]->neighbors.push_back(mapping[current->neighbors[i]]);
}
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: