题目:https://oj.leetcode.com/problems/clone-graph/
Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use#
as a separator for each node, and
,
as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}
.
The graph has a total of three nodes, and therefore contains three parts as separated by #
.
- First node is labeled as
0
. Connect node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
没有查答案自己很顺利的做出了这道题,看来最近做题还是有进步的,好开心啊~~(小菜鸟渣渣就是这么容易满足呀^_^)
题目意思:深拷贝一个无向图。
要考虑的问题:
1,首先图中的每个节点都要有一个拷贝;
2,每个节点有一个邻接表存储指向相邻节点的指针,不能直接拷贝,因为有可能存在拷贝指针时指针指向的节点还未拷贝的情况。(类似链表的深拷贝Copy List with Random Pointer这道题);
针对这两个问题,解题思路如下:
1,首先得拷贝每一个节点还必须要创建新旧节点的映射关系;可以使用map来存储;拷贝每一个节点涉及图的遍历,可以使用类似二叉树的层次遍历的方法,使用一个队列Queue来暂时存储还没有拷贝的节点。
2,拷贝每一个节点之后,再根据新旧节点的映射关系,复制每个新的节点的邻居节点,此时图中的每一个节点都已经存在不用担心指针指向的节点还未拷贝的情况。
AC代码:
/**
* 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 == NULL) return NULL;
//用来暂存还未拷贝的节点
queue<UndirectedGraphNode *> q;
q.push(node);
//建立新旧节点的映射关系
map<UndirectedGraphNode *,UndirectedGraphNode *> nodeMap;
while(!q.empty()){
UndirectedGraphNode *tmp = q.front();
q.pop();
if(!nodeMap.count(tmp)){
//复制当前节点
UndirectedGraphNode *newNode = new UndirectedGraphNode(tmp->label);
nodeMap[tmp] = newNode;
//把当前节点的邻居入队
for(int i = 0;i < tmp->neighbors.size();i++){
q.push(tmp->neighbors[i]);
}
}
}
//拷贝每个节点的邻居
map<UndirectedGraphNode *,UndirectedGraphNode *>::iterator iter = nodeMap.begin();
while(iter != nodeMap.end()){
for(int i = 0;i < iter->first->neighbors.size();i++){
iter->second->neighbors.push_back(nodeMap[iter->first->neighbors[i]]);
}
++iter;
}
return nodeMap[node];
}
};