题目:克隆图
来源:互联网 发布:2017苹果mac桌面壁纸 编辑:程序博客网 时间:2024/06/05 20:09
克隆一张无向图,图中的每个节点包含一个label和一个列表neighborsLintCode Online Judge的无向图序列化:
图节点有唯一的label。
使用#作为一个分隔符,分隔节点的label和每个相邻节点neighbors。比如,序列化图{0,1,2#1,2#2,2}共有三个节点,因此包含两个个分隔符#。
1、第一个节点label为0,存在边从节点0链接到节点1和节点2
2、第二个节点label为1,存在边从节点1连接到节点2
3、第三个节点label为2,存在边从节点2连接到节点2(本身),从而形成自环。
我们能看到如下的图:
1
/ \
/ \
0 --- 2
/ \
\_/
您在真实的面试中是否遇到过这个题?
Yes
样例
相关题目 Expand
解题思路:
BFS,用quene表示需要遍历的节点,map存储遍历过的节点
参考了
http://www.programcreek.com/2012/12/leetcode-clone-graph-java/
/*** Definition for undirected graph.* class UndirectedGraphNode {* int label;* ArrayList<UndirectedGraphNode> neighbors;* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }* };*/public class Solution { /** * @param node: A undirected graph node * @return: A undirected graph node */ public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { // write your code here if(node == null ) return null; Queue<UndirectedGraphNode> quene = new LinkedList<>(); HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>(); UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); quene.add(node); map.put(node, newNode); while(!quene.isEmpty()){ UndirectedGraphNode cur = quene.poll(); ArrayList<UndirectedGraphNode> neighbors = cur.neighbors; for(UndirectedGraphNode neighbor:neighbors){ if(!map.containsKey(neighbor)){ UndirectedGraphNode copy = new UndirectedGraphNode(neighbor.label); map.put(neighbor, copy); map.get(cur).neighbors.add(copy); quene.add(neighbor); }else{ map.get(cur).neighbors.add(map.get(neighbor)); } } } return newNode; }}
0 0
- 题目:克隆图
- 克隆图
- 克隆图
- 图位克隆法
- Clone Graph 克隆图
- LeetCode之克隆图
- 克隆图-LintCode
- LintCode:M-克隆图
- 克隆
- 克隆
- 克隆
- 克隆
- 克隆
- 克隆
- 克隆
- [LeetCode]Clone Graph 克隆图
- [LeetCode] 克隆图 Clone a Graph
- LeetCode | Clone Graph(克隆图)
- 10gR2中RAC环境中手工创建实例和监听(Linux/Unix)
- 【UVA10462】【好题】【次小生成树并查集算法】
- Number()、parseInt()和parseFloat()数值转换
- java Swing事件分发线程
- 8.28总结
- 题目:克隆图
- mysql修改表、字段、库的字符集
- 题目:全排列
- GPU加速计算-工具介绍
- 题目:分割回文串 II
- 实现一个函数,将字符串的每一个空格替换成 %20
- 初学UI,代码重构
- ORM进阶之Hibernate中关系映射
- Emgucv 使用级联分类器来检测物体