题目:无向图复制
Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
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 / \ \_/
题意:
克隆一个无向图。无向图中每一个节点包含一个标签和一个邻居节点集。
OJ的无向图序列化为:
每个节点都有唯一的标签。
使用#号作为每一个节点的分隔符,使用,号作为标签和每一个邻居节点的分隔符。
例如,序列化的无向图为{0, 1,2#1,2#2, 2}。
这个图总共有三个节点,并且包含由#号分隔开来的三个部分。
1、第一个节点被标记为0,连接节点0跟节点1和节点2;
2、第二个节点被标记为1,连接节点1跟节点2;
3、第三个节点被标记为2,连接节点2到其本身,因此形成一个自循环。
可视化的无向图结构如上图所示。
思路一:
这道题目的难点在于如何处理每个节点的neighbors,由于在深度拷贝每一个节点后,还要将其所有neighbors放到一个vector中,而如何避免重复拷贝呢?这道题好就好在所有节点值不同,所以我们可以使用哈希表来对应节点值和新生成的节点。对于图的遍历的两大基本方法是深度优先搜索DFS和广度优先搜索BFS,此题的两种解法可参见网友爱做饭的小莹子的博客,这里我们使用深度优先搜索DFS来解答此题。
代码:C++版:76ms
/** * 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); } UndirectedGraphNode *clone(UndirectedGraphNode *node, unordered_map<int, UndirectedGraphNode*> &umap) { if (!node) return node; 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; } };
思路二:
采用BFS实现,借助队列实现BFS的节点存储,每次复制一个节点之后,将其邻居节点均放入队列中,以备之后对邻居节点的复制使用。
代码:C++版:76ms
/** * 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 == nullptr) return nullptr; //map的key表示源节点,value表示复制的节点 unordered_map<const UndirectedGraphNode*, UndirectedGraphNode*> copied; //队列里面的每一个节点都已经复制过了 queue<const UndirectedGraphNode*> q; q.push(node); copied[node] = new UndirectedGraphNode(node->label); while (!q.empty()) { const UndirectedGraphNode *cur = q.front(); q.pop(); for (auto nbr : cur->neighbors) { //如果一个拷贝已经存在了 if (copied.find(nbr) != copied.end()) { copied[cur]->neighbors.push_back(copied[nbr]); } else { UndirectedGraphNode *newNode = new UndirectedGraphNode(nbr->label); copied[nbr] = newNode; copied[cur]->neighbors.push_back(newNode); q.push(nbr); } } } return copied[node]; } };