Make a deep copy of an undirected graph, there could be cycles in the original graph.

Assumptions

  • The given graph is not null

DFS

/*
* class GraphNode {
* public int key;
* public List<GraphNode> neighbors;
* public GraphNode(int key) {
* this.key = key;
* this.neighbors = new ArrayList<GraphNode>();
* }
* }
*/
public class Solution {
public List<GraphNode> copy(List<GraphNode> graph) {
// Write your solution here.
Map<GraphNode, GraphNode> map = new HashMap<>();
for (GraphNode node : graph) {
if (!map.containsKey(node)) {
map.put(node, new GraphNode(node.key));
}
dfs(node, map);
}
return new ArrayList<>(map.values());
} private void dfs(GraphNode node, Map<GraphNode, GraphNode> map) {
GraphNode newNode = map.get(node);
for (GraphNode gNode : node.neighbors) {
if (!map.containsKey(gNode)) {
map.put(gNode, new GraphNode(gNode.key));
}
newNode.neighbors.add(map.get(gNode));
}
}
}

BFS

/*
* class GraphNode {
* public int key;
* public List<GraphNode> neighbors;
* public GraphNode(int key) {
* this.key = key;
* this.neighbors = new ArrayList<GraphNode>();
* }
* }
*/
public class Solution {
public List<GraphNode> copy(List<GraphNode> graph) {
// Write your solution here.
Map<GraphNode, GraphNode> map = new HashMap<>();
for (GraphNode gNode: graph) {
map.put(gNode, new GraphNode(gNode.key));
}
for (GraphNode node : graph) {
GraphNode cpNode = map.get(node);
for (GraphNode nei: node.neighbors) {
cpNode.neighbors.add(map.get(nei));
}
}
return new ArrayList<>(map.values());
}
}

最新文章

  1. 【JS基础】
  2. 网页嵌入swf代码
  3. android 之 animations 动画
  4. js中的闭包之我理解
  5. MVC4 WebAPI(二)——Web API工作方式
  6. hive报错 Another instance of Derby may have already booted the database
  7. 自定义延时查询控件---valen
  8. Genymotion中SD卡目录在Eclipse中查看,以及创建SDCard
  9. DevExpress ASP.NET 使用经验谈(8)-ASPxGridView自定义列和基本事件
  10. 深入浅出Node.js (1) - Node简介
  11. vue传数据到模态框中
  12. Mac下面的SecureCRT以及破解方案详解
  13. 手写简单的jq雪花飘落
  14. 『最大M子段和 线性DP』
  15. MAC系统上不能调试华为手机
  16. Selenium的自我总结2_元素基本操作
  17. JavaScript中的栈和堆内存,作用域
  18. java反射基础
  19. js 识别汉字和全角字符
  20. quartz (一) 基于 Quartz 开发企业级任务调度应用

热门文章

  1. 笔记本如何不按Fn键就能实现F键的功能
  2. UVA - 11806 Cheerleaders (容斥原理)
  3. linux下的 sudo ln -s 源文件 目标文件
  4. Day3-T3
  5. C++ 编程学习(六) 函数
  6. ng-repeat动态生成的DOM如何获取宽度(封装好的方法)
  7. 全面掌握Nginx配置+快速搭建高可用架构 一 开启status页面检测服务状态
  8. CSS font-family 各字体一览表
  9. 实验吧web-易-上传绕过
  10. 查询内核符号链接的信息的API