LeetCode 133. Clone Graph
Solution1:
DFS/记忆化递归,参考网址:http://www.cnblogs.com/grandyang/p/4267628.html
真是一道记忆化递归的好题啊~
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
unordered_map<int, UndirectedGraphNode*> umap;
return clone(node, umap);
}
private:
UndirectedGraphNode *clone(UndirectedGraphNode *node,
unordered_map<int, UndirectedGraphNode*> &umap) {
if (!node) return node;//是针对node == NULL的情况的
if (umap.count(node->label)) return umap[node->label];
UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
umap[node->label] = newNode;
for (int i = 0; i < node->neighbors.size(); ++i) {
(newNode->neighbors).push_back(clone(node->neighbors[i], umap));
}
return newNode;
}
};
Solution2:
BFS,先记录一下自己的错代码。。。
参考网址:https://blog.csdn.net/windylai123/article/details/78134293
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution { //记忆化的BFS
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (!node) return NULL;
原图和新图节点一一对应
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> node_map;
UndirectedGraphNode *clone_node =
new UndirectedGraphNode(node->label);//首先克隆第一个结点
node_map[node] = clone_node; 建立map对应
//建一个队列,把头结点push进去
queue<UndirectedGraphNode *> node_queue;
node_queue.push(node);
while (!node_queue.empty()) {
UndirectedGraphNode *begin = node_queue.front();
node_queue.pop();
vector<UndirectedGraphNode *> temp = begin->neighbors;
for (int i = 0; i < temp.size(); i++) {
/*如果当前节点不在map里,则要生成新节点并放入队列*/
if (!node_map.count(temp[i])) {
UndirectedGraphNode * temp_node =
new UndirectedGraphNode(temp[i]->label);
node_map[temp[i]] = temp_node;
node_queue.push(temp[i]);
}
//生成当前节点的邻接节点
node_map[begin]->neighbors.push_back(node_map[temp[i]]);
}
}
return clone_node;
}
};