LeetCode 19 Clone Graph
来源:互联网 发布:windows快捷键设置 编辑:程序博客网 时间:2024/06/06 07:20
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
分析:
广度优先遍历,涉及队列的应用,
节点有没有访问过的标记,HashMap的应用。
/** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */public class Solution { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) return null; //广度优先遍历的常规技术,利用队列 Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>(); //HashMap用来标记节点有没有访问过 HashMap<UndirectedGraphNode,UndirectedGraphNode> hashMap = new HashMap<UndirectedGraphNode,UndirectedGraphNode>(); //先把第一个节点放进队列,完成初始化 queue.add(node); UndirectedGraphNode clone = new UndirectedGraphNode(node.label); hashMap.put(node, clone); //开始遍历 while(!queue.isEmpty()){ UndirectedGraphNode curr = queue.remove(); UndirectedGraphNode currClone = hashMap.get(curr); //对于当前节点的邻居 for(UndirectedGraphNode item : curr.neighbors){ //如果在hashMap里,说明已经访问过,建立指针关系即可 if(hashMap.containsKey(item)){ currClone.neighbors.add(hashMap.get(item)); }else{//如果没有在hashMap里,说明没有访问过,除了新建节点并建立指针关系外, //还要再hashMap里放入新对,并将没有访问过的节点入队 UndirectedGraphNode newItem = new UndirectedGraphNode(item.label); currClone.neighbors.add(newItem); hashMap.put(item, newItem); queue.add(item); } } } return clone; }}
0 0
- LeetCode 19 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] Clone Graph
- LeetCode OJ:Clone Graph
- Leetcode Clone Graph
- [Leetcode] Clone Graph (Java)
- Clone Graph - LeetCode
- 第一章:操作系统概述
- IOS-UIImageView 图片自适应大小
- 高等数学(上)期末考试试题(A)——卷一
- Wifi的密码长度有何限制
- Lua学习笔记 第十五章 模块与包
- LeetCode 19 Clone Graph
- 如何量化评价搜索引擎的结果质量
- IOS:修改NavigationController的后退按钮标题
- 横竖屏切换时Activity的生命周期变化
- UNIX Domain Socket IPC (sockaddr_un )
- IOS应用程序生命周期&启动周期函数
- 整数和浮点除法
- C#记事本自定义类(保存,统计汉字,查找,TreeView调用)
- QML BOOK 第十章 Multimedia