leetcode 133. Clone Graph

超、凢脫俗 2022-07-28 00:11 255阅读 0赞

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

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

遍历即可

  1. class Solution {
  2. public:
  3. UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
  4. if (node == NULL)
  5. return NULL;
  6. vector<UndirectedGraphNode*>que,nodelist,newnonelist;
  7. que.push_back(node); nodelist.push_back(node);
  8. while (!que.empty())
  9. {
  10. vector<UndirectedGraphNode*>newque;
  11. for (int i = 0; i < que.size(); i++)
  12. for (int j = 0; j < que[i]->neighbors.size(); j++)
  13. {
  14. if (find(nodelist.begin(), nodelist.end(), que[i]->neighbors[j]) == nodelist.end())
  15. {
  16. nodelist.push_back(que[i]->neighbors[j]);
  17. newque.push_back(que[i]->neighbors[j]);
  18. }
  19. }
  20. que = newque;
  21. }
  22. for (int i = 0; i < nodelist.size(); i++)
  23. {
  24. UndirectedGraphNode*n = new UndirectedGraphNode(nodelist[i]->label);
  25. newnonelist.push_back(n);
  26. }
  27. for (int i = 0; i < nodelist.size(); i++)
  28. {
  29. newnonelist[i]->neighbors.clear();
  30. for (int j = 0; j < nodelist[i]->neighbors.size(); j++)
  31. {
  32. int index = find(nodelist.begin(), nodelist.end(), nodelist[i]->neighbors[j]) - nodelist.begin();
  33. newnonelist[i]->neighbors.push_back(newnonelist[index]);
  34. }
  35. }
  36. return newnonelist[0];
  37. }
  38. };

accepted

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读

    相关 leetcode133. Clone Graph

    133. Clone Graph ![这里写图片描述][SouthEast] 这道题目的意思是:对一个无向图进行深拷贝,即需要申请一个新的空间,并将原来的无向图中的节点