[leedcode 133] Clone Graph
2015-07-26 15:56
302 查看
Clone an undirected graph. Each node in the graph contains a
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use
As an example, consider the serialized graph
The graph has a total of three nodes, and therefore contains three parts as separated by
First node is labeled as
Second node is labeled as
Third node is labeled as
Visually, the graph looks like the following:
labeland 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
#.
First node is labeled as
0. Connect node
0to both nodes
1and
2.
Second node is labeled as
1. Connect node
1to node
2.
Third node is labeled as
2. Connect node
2to 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<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */ public class Solution { 使用深度优先搜索。这样可以递归实现,如果是宽度优先,就要额外使用queue容器。 关键点: 1 这里的clone需要深度拷贝,就是要使用new操作了 2 防止回路无限循环,就要使用hash表,这里使用map记录访问过的节点。因为这里的label应该是唯一的才对,所以可以直接使用label作为关键字就可以。 public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node==null) return null; HashMap<Integer,UndirectedGraphNode> map=new HashMap<Integer,UndirectedGraphNode>(); return clone(node,map); } public UndirectedGraphNode clone(UndirectedGraphNode node,HashMap<Integer,UndirectedGraphNode> map){ if(map.containsKey(node.label)) return map.get(node.label); UndirectedGraphNode newNode=new UndirectedGraphNode(node.label); map.put(node.label,newNode);////注意标记的位置 for(UndirectedGraphNode n:node.neighbors){ newNode.neighbors.add(clone(n,map));///// } return newNode; } }
相关文章推荐
- 选择排序
- July Number zoj3436
- 大小写转换
- Oracle OLAP 与 OLTP 介绍
- 【峰回路转】Excel技巧百例 04.两个表的左连接
- iOS中对NSArray中自定义的对象进行排序
- Fragment
- 将tomcat添加为 linux service 服务
- Xamrin开发安卓笔记(二)
- HTML5基础20----Web Storage概述
- MySQL架构方案
- Ubuntu14.04.2安装搜狗输入法
- Tug of War(严格限制数量的二维费用背包)
- VS2015开发安卓应用笔记(一)
- 2.1 Qemu用户态 Machine与cpu管理
- matlab图像处理 笔记
- 第一条:了解Objective-C语言的起源
- error C2660: “Gdiplus::GdiplusBase::operator new”: 函数不接受 3 个参数(转)
- Machine Learning 1---Introduction
- Hbase总结(四)- Hbase与传统数据库的区别