题目:Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
思路:因为每个label是独一无二的,所以可以用map容器存储,这样也便于寻找。对图跑两遍,第一遍将所有的节点建立,并且将新旧节点关联,放进容器中。第二遍遍历时,将每个节点的neighbors添加进去即可。
代码如下:
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node==NULL)return NULL;
map<UndirectedGraphNode*,UndirectedGraphNode*> mark;
queue<UndirectedGraphNode*> l;
int i;
UndirectedGraphNode *t;
UndirectedGraphNode *p;
l.push(node);
while(!l.empty())
{
t=l.front();
l.pop();
p=new UndirectedGraphNode(t->label);
mark.insert(make_pair(t,p));
i=t->neighbors.size()-1;
for(;i>=0;i--)
{
if(mark.count(t->neighbors[i]))continue;
else
l.push(t->neighbors[i]);
}
}
vector<UndirectedGraphNode*> visit;
l.push(node);
while(!l.empty())
{
t=l.front();
l.pop();
i=t->neighbors.size()-1;
visit.push_back(t);
for(int j=0;j<=i;j++)
{
mark[t]->neighbors.push_back(mark[t->neighbors[j]]);
if(find(visit.begin(),visit.end(),t->neighbors[j])==visit.end())
{
visit.push_back(t->neighbors[j]);
l.push(t->neighbors[j]);
}
}
}
return mark[node];
}
};