您的位置:首页 > 其它

leetcode 133. Clone Graph

2016-03-25 22:33 375 查看
Clone an undirected graph. Each node in the graph contains a 
label
 and
a list of its 
neighbors
.

struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};

};

遍历即可

class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL)
return NULL;
vector<UndirectedGraphNode*>que,nodelist,newnonelist;
que.push_back(node); nodelist.push_back(node);
while (!que.empty())
{
vector<UndirectedGraphNode*>newque;
for (int i = 0; i < que.size(); i++)
for (int j = 0; j < que[i]->neighbors.size(); j++)
{
if (find(nodelist.begin(), nodelist.end(), que[i]->neighbors[j]) == nodelist.end())
{
nodelist.push_back(que[i]->neighbors[j]);
newque.push_back(que[i]->neighbors[j]);
}
}
que = newque;
}
for (int i = 0; i < nodelist.size(); i++)
{
UndirectedGraphNode*n = new UndirectedGraphNode(nodelist[i]->label);
newnonelist.push_back(n);
}
for (int i = 0; i < nodelist.size(); i++)
{
newnonelist[i]->neighbors.clear();
for (int j = 0; j < nodelist[i]->neighbors.size(); j++)
{
int index = find(nodelist.begin(), nodelist.end(), nodelist[i]->neighbors[j]) - nodelist.begin();
newnonelist[i]->neighbors.push_back(newnonelist[index]);
}
}
return newnonelist[0];
}
};


accepted
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: