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

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

https://oj.leetcode.com/problems/clone-graph/

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         / \         \_/

/** * Definition for undirected graph. * class UndirectedGraphNode { *     int label; *     List
neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList
(); } * }; */
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node)

这一题虽然说是图的克隆,但其实本质上就是无向图的全遍历。那么DFS和BFS在这里都是可以用的。就是用HashMap来进行路径记录避免循环路径。下面直接给出两段代码吧

DFS(实际上是一个bottom-up回收路径的过程):

public UndirectedGraphNode DFShelper(UndirectedGraphNode node, HashMap
visited){ if(visited.containsKey(node)) return visited.get(node); UndirectedGraphNode copy_node = new UndirectedGraphNode(node.label); visited.put(node, copy_node); for(UndirectedGraphNode n : node.neighbors){ copy_node.neighbors.add(DFShelper(n, visited)); } return copy_node; }
BFS:

public UndirectedGraphNode BFShelper(UndirectedGraphNode node){        Queue
node_queue = new LinkedList
(); HashMap
visited = new HashMap
(); UndirectedGraphNode res = new UndirectedGraphNode(node.label); visited.put(node, res); node_queue.add(node); while(!node_queue.isEmpty()){ UndirectedGraphNode cur_node = node_queue.poll(); UndirectedGraphNode copy_node = visited.get(cur_node); for(UndirectedGraphNode n : cur_node.neighbors){ UndirectedGraphNode copy_n = visited.containsKey(n) ? visited.get(n) : new UndirectedGraphNode(n.label); copy_node.neighbors.add(copy_n); if(!visited.containsKey(n))node_queue.add(n); visited.put(n, copy_n); } } return res; }
具体说一下哈希表的内容,键是原图的内容,值是拷贝的内容。所以每次DFS递归或者BFS循环的时候,总能在对应的点上取到对应的neighbors copy。BFS比较好理解,DFS实际上就是一个首先top-down遍历路径然后再bottom-up回收路径的一个做法。这在DFS上应该也是很常见的。

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

你可能感兴趣的文章
龙星课程: 局部性原理在计算机和分布式系统中的应用
查看>>
eclipse的奇怪的更新方式
查看>>
MIPS技术公司官方对linux的支持信息
查看>>
openflow简介
查看>>
windows7配置虚拟AP的脚本
查看>>
windows7定时关机脚本
查看>>
ARM流水线结构的发展(ARM7~ARM11)
查看>>
Dalvik: 从makefile入门
查看>>
常用浮点数常量
查看>>
三角函数的特殊值的结果
查看>>
奇怪的X86
查看>>
有意思的C语言
查看>>
Basic Block
查看>>
CompilationUnit
查看>>
要以最自然的方式驾驭大数据
查看>>
日本用大数据技术预测流感 预测与分析结果精确
查看>>
我们为什么需要大数据技术?
查看>>
大数据使超级计算机迎来第二春
查看>>
多地政府探索“大数据”惠民之道 信息垄断须打破
查看>>
民营经济的支撑不可或缺
查看>>