问题描述
本题要求复制一个无向图,图中每个节点都包含一个标签和它的邻居列表
我们无向图用以下的方法序列化:
节点的标签是互不相同的,
我们使用“#”作为节点之间的分隔符,使用“,”作为节点标签和节点的节点邻居的分隔符。
例如:现在有一个序列化的无向图{0,1,2#1,2#2,2}.
这个无向图一共有3个节点,因此序列被#分隔成三部分
第一个节点的标签是0,节点0和节点1,节点2之间有边
第二个节点的标签是1,节点1和节点2之间有边
第三个节点的标签是2,节点2和节点2(它自己)之间有边,形成了自环
这个无向图如下图所示
1↵ / ↵ / ↵ 0 — 2↵ / ↵ _/↵
解法
- 使用队列+广搜
- 使用map来将原结点和新结点对应
- map也可以用来标注在搜索中该结点是否已经被访问过
- 当map添加新结点时,添加pair对,当广搜访问原结点的neigh时,新结点添加原结点neigh在map中的结点作为neigh
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
typedef UndirectedGraphNode* node;
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node1) {
if(node1==NULL)return NULL;
map<node,node>m;
queue<node>q;
q.push(node1);
while(!q.empty()){
node t = q.front();
node newnode;
//未被访问过
if(m.find(t)==m.end()){
newnode = new UndirectedGraphNode(t->label);
m.insert(pair<node,node>(t,newnode));//结点访问过标注
}
newnode = m[t];
for(int i=0;i<t->neighbors.size();i++){
node temp = t->neighbors[i];
if(m.find(temp)==m.end()){//如果没访问过
node newnode2 = new UndirectedGraphNode(temp->label);
m.insert(pair<node,node>(temp,newnode2));
q.push(temp);//当没访问过,入队
}
newnode->neighbors.push_back(m[temp]);
}
q.pop();
}
return m[node1];
}
};