Lintcode137 Clone Graph solution 题解
来源:互联网 发布:方舟生存进化画面优化 编辑:程序博客网 时间:2024/06/16 09:27
【题目描述】
Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors.
How we serialize an undirected graph:
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 as0. Connect node0to both nodes1and2.
2.Second node is labeled as1. Connect node1to node2.
3.Third node is labeled as2. Connect node2to node2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
克隆一张无向图,图中的每个节点包含一个label和一个列表neighbors。
数据中如何表示一个无向图?http://www.lintcode.com/help/graph/
你的程序需要返回一个经过深度拷贝的新图。这个新图和原图具有同样的结构,并且对新图的任何改动不会对原图造成任何影响。
样例
比如,序列化图{0,1,2#1,2#2,2}共有三个节点, 因此包含两个个分隔符#。
1.第一个节点label为0,存在边从节点0链接到节点1和节点2
2.第二个节点label为1,存在边从节点1连接到节点2
3.第三个节点label为2,存在边从节点2连接到节点2(本身),从而形成自环。
我们能看到如下的图:
1
/ \
/ \
0 --- 2
/ \
\_/
【题目链接】
www.lintcode.com/en/problem/clone-graph/
【题目解析】
这道题考察的是对图的遍历和利用HashMap拷贝的方法。
对图的遍历就是两个经典的方法DFS和BFS。BFS经常用Queue实现,DFS经常用递归实现(可改为栈实现)。
拷贝方法是用用HashMap,key存原始值,value存copy的值,用DFS,BFS方法遍历帮助拷贝neighbors的值。
【参考答案】
www.jiuzhang.com/solutions/clone-graph/
- Lintcode137 Clone Graph solution 题解
- [LeetCode] Clone Graph, Solution
- LeetCode题解:Clone Graph
- LeetCode题解:Clone Graph
- Lintcode178 Graph Valid Tree solution 题解
- LeetCode 题解(22): Clone Graph
- LeetCode题解–133. Clone Graph
- Lintcode176 Route Between Two Nodes in Graph solution 题解
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- Clone Graph
- HDU5514 Frogs
- android开发笔记汇总(一)
- Java 课堂笔记 3
- 匿名内部类是什么?为什么其访问外部变量必须是finally的?
- Codeforces 861 D. Polycarp's phone book (trie)
- Lintcode137 Clone Graph solution 题解
- 隐藏/显示左frame栏
- 浅析web Storage
- Python 符号 自学总结(学习中)
- Find K Min
- 2017 ACM-ICPC 亚洲区(西安赛区)网络赛 I. Barty's Computer(哈希||字典树)
- Centos安装redis
- poj3352 Road Construction 边双连通分量tarjan算法
- Nginx的优缺点