博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Clone Graph
阅读量:5862 次
发布时间:2019-06-19

本文共 2056 字,大约阅读时间需要 6 分钟。

Clone Graph

BFS

Time Complexity

O(N)
Space Complexity
O(N)

思路

Do a BFS traversal of the graph and while visiting a node make a clone node of it.

Use a hashmap to check if the node has already been created.

Key value: reference of original node
Value: reference of cloned node

How to connect clone nodes?

After all graph nodes has been made, get the corresponding cloned node u, then visit all the neighboring nodes of u and then connect the corresponding clone node then push it into queue.

代码

public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {    //coner case    if(node == null) return null;    Map
map = new HashMap
(); Queue
queue = new LinkedList
(); queue.offer(node); UndirectedGraphNode root = new UndirectedGraphNode(node.label); map.put(node, root); while(!queue.isEmpty()){ UndirectedGraphNode cur = queue.poll(); for(UndirectedGraphNode n : cur.neighbors){ if(!map.containsKey(n)){ map.put(n, new UndirectedGraphNode(n.label)); queue.offer(n); } map.get(cur).neighbors.add(map.get(n)); } } return root;}

DFS

Time Complexity

O(N)
Space Complexity
O(N)

思路

You can think it as a tree, the level is how many nodes in the graph, each level represents all the neighbors of the nodes, after create all cloned nodes, then connect them together. Use the hashmap method as BFS method.

代码

public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {    if(node == null) return node;    Map
map = new HashMap
(); UndirectedGraphNode root = new UndirectedGraphNode(node.label); map.put(node, root); helper(node, map); return root;}private void helper(UndirectedGraphNode node, Map
map){ for(UndirectedGraphNode n : node.neighbors){ if(!map.containsKey(n)){ map.put(n, new UndirectedGraphNode(n.label)); helper(n, map); } map.get(node).neighbors.add(map.get(n)); }}

转载地址:http://zugjx.baihongyu.com/

你可能感兴趣的文章
套接字socket
查看>>
校验IPv4和IPv6地址和URL地址
查看>>
[绩效管理]可度量绩效管理模型第一阶段应用方法群简述
查看>>
Oracle性能分析1:开启SQL跟踪和获取trace文件
查看>>
python之路-------字符串与正則表達式
查看>>
Lintcode---将二叉树拆成链表
查看>>
MVC5+EF6 入门完整教程四
查看>>
easyui------设置datagrid('getEditor')时焦点问题
查看>>
[转]a-mongodb-tutorial-using-c-and-asp-net-mvc
查看>>
Bootstrap图标
查看>>
在 linux 下使用 CMake 构建应用程序【转】
查看>>
关于程序性能优化基础的一些个人总结
查看>>
socket.io笔记三之子命名空间的socket连接
查看>>
Building Apps for Windows 10 on LattePanda–Jump Start
查看>>
动画中的模块化设计
查看>>
微信公众平台搭建与开发(二)开发模式的搭建和关键词回复
查看>>
Activiti 用户手册
查看>>
ReactiveSwift源码解析(七) Signal的CombineLatest的代码实现
查看>>
通过Fiddler肆意修改接口返回数据进行测试
查看>>
Java设计模式——工厂模式
查看>>