欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

每天一道LeetCode-----复制无向图

发布时间:2024/4/19 66 豆豆
生活随笔 收集整理的这篇文章主要介绍了 每天一道LeetCode-----复制无向图 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Clone Graph

原题链接Clone Graph

复制一个无向图

遍历一遍图就可以了

代码如下

/*** Definition for undirected graph.* struct UndirectedGraphNode {* int label;* vector<UndirectedGraphNode *> neighbors;* UndirectedGraphNode(int x) : label(x) {};* };*/ class Solution { public:UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {unordered_map<int, UndirectedGraphNode*> hash;return cloneGraph(node, hash);} private:UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node, unordered_map<int, UndirectedGraphNode*>& hash){if(!node) return nullptr;/* hash记录着label对应的节点,如果已经复制过,就直接返回 */if(hash.find(node->label) != hash.end())return hash[node->label];auto res = new UndirectedGraphNode(node->label);hash[res->label] = res;for(auto ptr : node->neighbors)res->neighbors.emplace_back(cloneGraph(ptr, hash));return res;} };

本题主要就是深度优先遍历无向图,需要注意的是重复问题

总结

以上是生活随笔为你收集整理的每天一道LeetCode-----复制无向图的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。