133. Clone Graph (Medium)
Clone an undirected graph. Each node in the graph contains alabel
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
/ \
\_/
Solution 1: DFS
这道无向图的复制问题和之前的拷贝带有随机指针的链表有些类似,那道题的难点是如何处理每个节点的随机指针,这道题目的难点在于如何处理每个节点的neighbors,由于在深度拷贝每一个节点后,还要将其所有neighbors放到一个vector中,而如何避免重复拷贝呢?这道题好就好在所有节点值不同,所以我们可以使用哈希表来对应节点值和新生成的节点。对于图的遍历的两大基本方法是深度优先搜索DFS和广度优先搜索BFS,此题的两种解法可参见网友爱做饭的小莹子的博客,这里我们使用深度优先搜索DFS来解答此题,代码如下:
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> m;
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (!node) return NULL;
if (m.find(node) == m.end()) {
m[node] = new UndirectedGraphNode(node->label);
for (auto& x: node->neighbors) {
m[node]->neighbors.push_back(cloneGraph(x));
}
}
return m[node];
}
};
Solution 2: BFS
class Solution {
public:
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> m;
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (!node) return NULL;
UndirectedGraphNode* copy = new UndirectedGraphNode(node -> label);
m[node] = copy;
queue<UndirectedGraphNode*> q;
q.push(node);
while(!q.empty()) {
UndirectedGraphNode* cur = q.front(); q.pop();
for (UndirectedGraphNode* neigh: cur->neighbors) {
if (m.find(neigh) == m.end()) {
m[neigh] = new UndirectedGraphNode(neigh->label);
q.push(neigh);
}
m[cur]->neighbors.push_back(m[neigh]);
}
}
return copy;
}
};