137.Clone Graph-克隆图(中等题)
来源:互联网 发布:中国企业网络黄页 编辑:程序博客网 时间:2024/06/04 19:32
克隆图
题目
克隆一张无向图,图中的每个节点包含一个 label 和一个列表 neighbors。
数据中如何表示一个无向图?http://www.lintcode.com/help/graph/
你的程序需要返回一个经过深度拷贝的新图。这个新图和原图具有同样的结构,并且对新图的任何改动不会对原图造成任何影响。样例
比如,序列化图 {0,1,2#1,2#2,2} 共有三个节点, 因此包含两个个分隔符#。
第一个节点label为0,存在边从节点0链接到节点1和节点2
第二个节点label为1,存在边从节点1连接到节点2
第三个节点label为2,存在边从节点2连接到节点2(本身),从而形成自环。
我们能看到如下的图:题解
/** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * ArrayList<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */public class Solution{ public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node == null) { return null; } ArrayList<UndirectedGraphNode> nodes = new ArrayList<UndirectedGraphNode>(); HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); nodes.add(node); map.put(node, new UndirectedGraphNode(node.label)); int start = 0; while (start < nodes.size()) { UndirectedGraphNode head = nodes.get(start++); for (int i = 0; i < head.neighbors.size(); i++) { UndirectedGraphNode neighbor = head.neighbors.get(i); if (!map.containsKey(neighbor)) { map.put(neighbor, new UndirectedGraphNode(neighbor.label)); nodes.add(neighbor); } } } for (int i = 0; i < nodes.size(); i++) { UndirectedGraphNode newNode = map.get(nodes.get(i)); for (int j = 0; j < nodes.get(i).neighbors.size(); j++) { newNode.neighbors.add(map.get(nodes.get(i).neighbors.get(j))); } } return map.get(node); }}
Last Update 2016.10.16
0 0
- 137.Clone Graph-克隆图(中等题)
- Clone Graph 克隆图
- LeetCode | Clone Graph(克隆图)
- LeetCode 133. Clone Graph(克隆图)
- [LeetCode]Clone Graph 克隆图
- [LeetCode] 克隆图 Clone a Graph
- 178.Graph Valid Tree-图是否是树(中等题)
- java的克隆(Clone)
- 176.Route Between Two Nodes in Graph-图中两个点之间的路线(中等题)
- leetcode_c++:图:Clone Graph(133)
- LeetCode(133) Clone Graph
- 133. Clone Graph(DFS)
- 算法(六)Clone Graph
- 375.Clone Binary Tree-克隆二叉树(容易题)
- clone 克隆
- Medium 133题 Clone Graph(必须再做!!!)
- Clone Graph
- Clone Graph
- URAL1222
- hdu 1799 循环多少次?(排列组合,思路)
- Spark程序设计——Scala
- 网络基础
- Python列表
- 137.Clone Graph-克隆图(中等题)
- Python元组
- 《MySQL相关文章索引(2)》
- Python字符串
- # IntelliJ IDEA 2016.2.4 注册码 破解 激活教程
- 移动端获取数据列表
- 关于ListView优化陋解
- 听课学习方法
- html感染型病毒