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

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

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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

 

Visually, the graph looks like the following:

1      / \     /   \    0 --- 2         / \         \_/

 

直接用HashMap来做应该是最简单的,这个对十字链表也可以。使用hashmap来存储node的对应关系。

1 /** 2  * Definition for undirected graph. 3  * class UndirectedGraphNode { 4  *     int label; 5  *     ArrayList
neighbors; 6 * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList
(); } 7 * }; 8 */ 9 public class Solution {10 HashMap
map = new HashMap
();11 public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {12 map.clear();13 return cloneNode(node);14 }15 16 private UndirectedGraphNode cloneNode(UndirectedGraphNode node)17 {18 if (node == null) return null;19 if (map.containsKey(node)) return map.get(node);20 else21 {22 UndirectedGraphNode copy = new UndirectedGraphNode(node.label);23 map.put(node, copy);24 for (UndirectedGraphNode n : node.neighbors)25 {26 copy.neighbors.add(cloneNode(n));27 }28 return copy;29 }30 }31 }

 

 

 

转载于:https://www.cnblogs.com/reynold-lei/p/3375354.html

你可能感兴趣的文章
【LeeCode】 15. 3Sum 解题小结
查看>>
软件工程 个人作业3 案例分析
查看>>
2018 noip AFO? 祭
查看>>
MVC5 + EF6 入门完整教程二
查看>>
oc和javascript互相调用
查看>>
新闻列表布局中ie6的变态
查看>>
nginx log日志分割
查看>>
RC4加密算法
查看>>
2048游戏原理(二)
查看>>
springboot导入excel到mysql
查看>>
解决flask的端口占用
查看>>
第一次作业+105032014087
查看>>
vue mounted组件的使用
查看>>
RepotService添加空格符
查看>>
IP Address Configuration on Linux (RHEL 5.4)
查看>>
JS浏览器检测判断
查看>>
使用linux内核hrtimer高精度定时器实现GPIO口模拟PWM,【原创】
查看>>
Xshell配色方案啊【学习笔记】
查看>>
10秒钟执行一次计划任务
查看>>
Java魔法堂:类加载机制入了个门
查看>>