题目要求:
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 node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
分析:
这道题是Leetcode上关于搜索算法的一道medium难度的题,要求完整复制一个图,因此需要遍历图的每一个节点,同时生成一个对应点。这就需要用到map这个关联容器,将原节点和新节点一一对应,这样能够保存已生成的子节点,还能准确地获知当前遍历到的节点位置,知道下一步是生成子节点还是邻节点。而搜索图的方法自然是DFS和BFS了,就本题而言,DFS会更简单一些。
具体做法:
DFS:
- step1:用当前节点的value值生成一个新节点,并与原节点建立map对应关系。
- step2:递归遍历当前节点的每一个邻节点,并在回溯时生成当前节点的邻接节点序列。
- step3:返回当前节点,最终得到新的根节点
DFS代码:
class Solution {
public:
map<UndirectedGraphNode *, UndirectedGraphNode *> mp; //原图和新图节点一一对应
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL) return NULL;
if (mp.find(node) == mp.end()){
UndirectedGraphNode *root = new UndirectedGraphNode(node->label); //复制出新的节点
mp[node] = root; //建立map对应
for (int i = 0; i < node->neighbors.size(); i++){
cloneGraph(node->neighbors[i]); //递归遍历每一个邻节点
mp[node]->neighbors.push_back(mp[node->neighbors[i]]); //回溯时生成当前节点的邻接节点序列
}
}
return mp[node];
}
};
BFS:
- step1:用当前节点的value值生成一个新节点,并与原节点建立map对应关系。
- step2:建立队列,push根节点到队列中,每次取出一个节点,将其邻接节点列表push到队列末尾,重复循环直到队列为空。
- step3:循环遍历的同时生成当前节点的邻接节点,一边循环一边复制。
- step4:返回当前节点,最终得到新的根节点
BFS代码:
class Solution {
public:
map<UndirectedGraphNode *, UndirectedGraphNode *> mp; //原图和新图节点一一对应
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL) return NULL;
UndirectedGraphNode *root = new UndirectedGraphNode(node->label); //复制出新的节点
mp[node] = root; //建立map对应
queue<UndirectedGraphNode *> q;
q.push(node);
while (!q.empty()){
UndirectedGraphNode *begin = q.front();
q.pop();
vector<UndirectedGraphNode *> ends = begin->neighbors;
for (int i = 0; i < ends.size(); i++){
/*如果当前节点不在map里,则要生成新节点并放入队列*/
if (mp.find(ends[i]) == mp.end()){
UndirectedGraphNode *neigh = new UndirectedGraphNode(ends[i]->label);
mp[ends[i]] = neigh;
q.push(ends[i]);
}
mp[begin]->neighbors.push_back(mp[ends[i]]); //生成当前节点的邻接节点
}
}
return root;
}
};