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

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

题目描述如下:

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;因而总会重复遍历;看了别人的代码之后才恍然大悟,Java编程思想看了不用就是没用啊。。改正后代码如下:

public class Solution {    public static int cycleCount = 0;    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {        HashMap
checker = new HashMap
(); return cloneGraph(node, checker); } public UndirectedGraphNode cloneGraph(UndirectedGraphNode node, HashMap
checker){ if(node == null) return null; if(checker.containsKey(node.label)) return checker.get(node.label); UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); checker.put(node.label, newNode); for(UndirectedGraphNode n : node.neighbors){ newNode.neighbors.add(cloneGraph(n, checker)); } return newNode; }}

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

你可能感兴趣的文章
如何将Java String转换为byte []?
查看>>
ng-if和ng-show / ng-hide有什么区别
查看>>
用Java复制文件的标准简洁方法?
查看>>
删除可能不存在的文件的大多数pythonic方式
查看>>
如何在Eclipse中为Java文本编辑器更改字体大小?
查看>>
我们应该@Override接口的方法实现吗?
查看>>
ng-repeat定义次数而不是重复数组?
查看>>
选择语句以查找某些字段的重复项
查看>>
JavaScript ES6类中的私有属性
查看>>
java项目之——坦克大战09
查看>>
java项目之——坦克大战10
查看>>
java项目之——坦克大战11
查看>>
用sed批量替换文件中的字符
查看>>
顶级域名注册分布统计:2006年09月 .com .de .net .uk .cn
查看>>
雅虎通可以批量添加MSN用户了
查看>>
速度比较:GMail/MSN/Yahoo!Mail
查看>>
搜索引擎来路关键词的挖掘:百度统计的高级分析报告导出获取来源关键词
查看>>
C/C++题目--拷贝构造函数概念
查看>>
C/C++题目--深复制与浅复制
查看>>
数据结构教程--李春葆版(总结)之线性表-顺序存储结构练习题
查看>>