Leetcode 133. Clone Graph
来源:互联网 发布:标准数据公司 编辑:程序博客网 时间:2024/06/06 06:44
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
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node == null) return null; UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); HashMap<Integer, UndirectedGraphNode> map = new HashMap(); map.put(newNode.label, newNode); LinkedList<UndirectedGraphNode> queue = new LinkedList(); queue.add(node); while (!queue.isEmpty()) { UndirectedGraphNode n = queue.pop(); for (UndirectedGraphNode neighbor : n.neighbors) { if (!map.containsKey(neighbor.label)) { map.put(neighbor.label, new UndirectedGraphNode(neighbor.label)); queue.add(neighbor); } map.get(n.label).neighbors.add(map.get(neighbor.label)); } } return newNode; }
DFS
Map<Integer, UndirectedGraphNode> map = new HashMap<>(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { return dfs(node); } private UndirectedGraphNode dfs(UndirectedGraphNode node) { if (node == null) return null; if (map.containsKey(node.label)) return map.get(node.label); UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(newNode.label, newNode); for (UndirectedGraphNode neighbor : node.neighbors) { newNode.neighbors.add(dfs(neighbor)); } return newNode; }
阅读全文
0 0
- LeetCode 133. Clone Graph
- [Leetcode] 133. Clone Graph
- [leetcode] 133.Clone Graph
- Leetcode 133. Clone Graph
- 133. Clone Graph LeetCode
- LeetCode 133. Clone Graph
- leetcode 133. Clone Graph
- LeetCode *** 133. Clone Graph
- leetcode-133. Clone Graph
- LeetCode 133. Clone Graph
- [LeetCode] 133. Clone Graph
- LeetCode: 133. Clone Graph
- Leetcode-133. Clone Graph
- Leetcode 133. Clone Graph
- LeetCode 133. Clone Graph
- leetcode 133. Clone Graph
- [LeetCode]133. Clone Graph
- 【leetcode】133. Clone Graph
- 机器学习知识点
- iOS 某一个界面实现强制横屏
- android api gui 学习笔记---Fragment(片段)
- 进程无法在“WIN-XXX”上执行“sp_repldone/sp_replcounters”
- win10使用IIS发布ftp
- Leetcode 133. Clone Graph
- 后台开发遇到的问题:struts2 s:text无法传值
- 单链表的快速排序
- Crixalis's Equipment
- PowerShellGet系列(二):用PowerShellGet管理你的模块包
- 批处理(bat)实现SQLServer数据库备份与还原
- linux文件权限管理
- Statement和Expression的用法
- 2.2 贝叶斯决策论——连续特征