LeetCode题解:Clone Graph
来源:互联网 发布:大数据架构师证书 编辑:程序博客网 时间:2024/05/18 01:17
Clone Graph
Clone an undirected graph. Each node in the graph contains a label
and a list of itsneighbors
.
首先对这个图进行搜索,深度优先广度优先是任意的。每碰到一个之前未遇到的结点则创造一个相应的新结点与这个结点对照,同时新结点的所有邻居仍然和原始结点的邻居相同。
然后更新新结点的邻居信息,在之前的搜索中新旧结点的对应关系是已知的,简单的复制即可。
题解:
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */class Solution {public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if (node == nullptr) return nullptr; using UGN_t = UndirectedGraphNode; using pUGN_t = UGN_t*; map<pUGN_t, pUGN_t> old_new; set<pUGN_t> visited; queue<pUGN_t> to_be_visited; // traverse the node and duplicate them, // including the neighbors to_be_visited.push(node); while(!to_be_visited.empty()) { pUGN_t visiting = to_be_visited.front(); to_be_visited.pop(); // mark it visited visited.insert(visiting); // duplicate the node old_new[visiting] = new UndirectedGraphNode(visiting->label); copy(begin(visiting->neighbors), end(visiting->neighbors), back_inserter(old_new[visiting]->neighbors)); // discover new neighbors for(auto nbs : visiting->neighbors) if (visited.find(nbs) == end(visited)) // unvisited to_be_visited.push(nbs); } // traverse the new nodes and update all neighbors for(auto p : old_new) for(auto& nbs: p.second->neighbors) nbs = old_new[nbs]; return old_new[node]; }};
- LeetCode题解:Clone Graph
- LeetCode题解:Clone Graph
- LeetCode 题解(22): Clone Graph
- LeetCode题解–133. Clone Graph
- LeetCode[Graph]: Clone Graph
- [LeetCode] CLone Graph
- LeetCode:Clone Graph
- [leetcode]Clone Graph
- Leetcode: Clone Graph
- [LeetCode] Clone Graph
- [LeetCode]Clone Graph
- leetcode Clone Graph
- leetcode-Clone Graph
- LeetCode | Clone Graph
- Leetcode: Clone Graph
- [LeetCode] Clone Graph
- LeetCode OJ:Clone Graph
- Leetcode Clone Graph
- Xcode的working directory
- 嵌入式编程中关于const,static,extern,volatile的用法
- [LeetCode] Word Break II
- LeetCode题解:Spiral Matrix I and II
- 德国波恩出差记(一)
- LeetCode题解:Clone Graph
- Generate Parentheses 产生所有括号组合 @LeetCode
- Linux Ramdisk启动方式下文件系统兼容性快速排查。
- 企业软件管理FileWave
- const char * ptr;char * const cp 的区别
- LeetCode题解:Remove Duplicates from Sorted Array I and II
- hdoj1106 ( strtok函数 )
- OSX: 切换10.9用户桌面壁纸的脚本
- 推荐一个git源码托管网站