[LeetCode]Clone Graph
来源:互联网 发布:mac 虚拟机 游戏 编辑:程序博客网 时间:2024/06/05 17:53
Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use#
as a separator for each node, and ,
as a separator for node label and each neighbor of the node.As an example, consider the serialized graph {0,1,2#1,2#2,2}
.
The graph has a total of three nodes, and therefore contains three parts as separated by #
.
- First node is labeled as
0
. Connect node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
BFS,用hash来存储新的图和旧图的一一对应关系的点,采用BFS搜索。然后对每一个点存相邻点。
/** * 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<UndirectedGraphNode * ,UndirectedGraphNode *> NodeMap; //和克隆图之间的Map这样可以一次遍历完 queue<UndirectedGraphNode *> Qq; if(node == NULL) return node; Qq.push(node); while(!Qq.empty()){ UndirectedGraphNode *top = Qq.front(); Qq.pop(); if(NodeMap.count(top)==0){//没有节点 UndirectedGraphNode * Temp = new UndirectedGraphNode(top->label); NodeMap[top] = Temp; } //保存相邻节点 for(auto it = top->neighbors.begin(); it!=top->neighbors.end(); ++it){ UndirectedGraphNode *adj = *it; if(NodeMap.count(adj)==0){//没有该节点,创建节点,同时间也避免了环,之前遍历过的节点不会再遍历 UndirectedGraphNode *Temp = new UndirectedGraphNode(adj->label); NodeMap[adj] = Temp; Qq.push(adj); } NodeMap[top]->neighbors.push_back(NodeMap[adj]); //给定字节点所有链接节点,如果有环也会保留,因为没有入队列 } } return NodeMap[node]; }};
0 0
- 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] Clone Graph
- LeetCode OJ:Clone Graph
- Leetcode Clone Graph
- [Leetcode] Clone Graph (Java)
- Clone Graph - LeetCode
- 【leetcode】Clone Graph
- wxWidgets教程(4)- 绘图
- objc/runtime.h 相关
- xcode快捷键和mac快捷键
- 数据结构(树转线性)最近公共祖先
- HTTP协议理解与应用总结
- [LeetCode]Clone Graph
- servlet/filter/listener/interceptor区别与联系
- 计蒜客 挑战难题 X的平方根
- ios开发中归档的使用
- c++学习笔记1(指针和引用)
- JavaBean技术
- 在Ubuntu14.04上部署使用SMART HTTP的Git服务器
- 如何判断一个类是否支持某属性和方法以及如何判断IOS的版本
- 从头认识多线程-1.11 suspend和resume缺点-独占