133. Clone Graph
来源:互联网 发布:js查看cookie过期时间 编辑:程序博客网 时间:2024/06/06 07:49
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 node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
code
/** * Definition for undirected graph. * public class UndirectedGraphNode { * public int label; * public IList<UndirectedGraphNode> neighbors; * public UndirectedGraphNode(int x) { label = x; neighbors = new List<UndirectedGraphNode>(); } * }; */public class Solution { private Dictionary<int,UndirectedGraphNode> dict = new Dictionary<int,UndirectedGraphNode>(); public UndirectedGraphNode CloneGraph(UndirectedGraphNode node) { if(node==null) return node; if(dict.ContainsKey(node.label)) return dict[node.label]; //self-cycle UndirectedGraphNode clonenode = new UndirectedGraphNode(node.label); dict.Add(node.label,clonenode); foreach(var item in node.neighbors){ //add neighbors node clonenode.neighbors.Add(CloneGraph(item)); } return clonenode; }}
阅读全文
2 0
- LeetCode 133. Clone Graph
- [Leetcode] 133. Clone Graph
- [leetcode] 133.Clone Graph
- 133. Clone Graph
- Leetcode 133. Clone Graph
- 133. Clone Graph LeetCode
- 133. Clone Graph
- LeetCode 133. Clone Graph
- leetcode 133. Clone Graph
- 133. Clone Graph
- 133. Clone Graph
- LeetCode *** 133. Clone Graph
- leetcode-133. Clone Graph
- LeetCode 133. Clone Graph
- 133. Clone Graph
- 133. Clone Graph
- 133. Clone Graph
- 133. Clone Graph
- 图论专题 菜肴制作 矩阵游戏 魔法森林 飞行路线
- 我工作过的系
- BZOJ 3505 数三角形
- 差分约束+tarjin [Poi2012]Festival
- [POI2007]洪水pow 并查集
- 133. Clone Graph
- 【二分图匹配入门专题1】D
- DataReader和DataAdapter的区别
- FTPrep, 38 Read and Count
- 【二分图匹配入门专题1】F
- ubuntu如何实现双屏显示
- Linux DMA meory简述
- 面向对象的c语言
- Self08.13-1