Clone Grap
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 / \ \_/
题目意思很简单,就是给一个可以有回路的图,从任意给的节点开始,将这个图复制一遍,返回任给的这个节点的复制节点。
算法思想:
我们可以采用广度优先搜索的方法来遍历这张图,根据每个节点进行复制,所以用到了队列这个数据结构,遍历各节点时,将该节点指针push到队列中;
因为同时考虑到两种情况:1、回路如何判重;2、怎样实现已知节点与根据该节点复制的节点的一一对应,所以我用到了map这个数据结构,实现
已知节点指针到复制节点指针的映射。
class Solution{
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node){
if(!node)return NULL;
UndirectedGraphNode *head=new UndirectedGraphNode(node->label);
queue<UndirectedGraphNode *> store;
map<UndirectedGraphNode *,UndirectedGraphNode *> mp;
map<UndirectedGraphNode *,UndirectedGraphNode *>::iterator it;
store.push(node);
mp.insert(pair<UndirectedGraphNode *,UndirectedGraphNode *>(node,head));
while(!store.empty()){
UndirectedGraphNode *cur=store.front();
UndirectedGraphNode *newNode=mp.find(cur)->second;//根据cur节点到该复制节点
store.pop();
for(int i=0;i<cur->neighbors.size();i++){
it=mp.find(cur->neighbors[i]);
if(it!=mp.end()){//如果该节点已经存在,说明有回路
newNode->neighbors.push_back(it->second);
continue;
}
UndirectedGraphNode *next=cur->neighbors[i];
UndirectedGraphNode *t=new UndirectedGraphNode(next->label);
newNode->neighbors.push_back(t);
store.push(next);
mp.insert(pair<UndirectedGraphNode *,UndirectedGraphNode *>(next,t));
}
}
return head;
}
};