[LintCode] Clone Graph
2015-10-29 10:55
260 查看
Clone Graph
Clone an undirected graph. Each node in the graph contains alabeland 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 / \ \_/
SOLUTION:
思路上讲这个题可以分两个部分1,遍历图 2,clone图。
遍历需要用到BFS,基本图的搜索都是BFS,那么也就是要用到queue,先讲node进入队列,然后pop的时候访问他的所有neighbors,把没访问过的neighbor放入队列中,依次pop重复以上操作,在这个过程中将入栈的neighbor存入hashmap中,以便以后确认入栈时是否曾经入队列过,保证只放没遍历过的点入队列。在这个题里,用一个指针+ArrayList模拟一个队列也是没问题的。
clone时,就是要做deep copy。用newnode作为一个map里指向copynode的指针,再次遍历容器里的node,把原来点的neighbors在map里的映射(BFS时候会克隆到)加入新newnode的neighbors里面。
最后return map里的node的映射就可以了
public class Solution { /** * @param node: A undirected graph node * @return: A undirected graph node */ public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node == null){ return null; } //because I need the collection 2 times, so I can't use queue, then I choice ArrayList and a pointer(start) ArrayList<UndirectedGraphNode> nodes = new ArrayList<UndirectedGraphNode>(); HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); nodes.add(node); map.put(node, new UndirectedGraphNode(node.label)); int start = 0; //clone nodes while (start < nodes.size()){ UndirectedGraphNode cur = nodes.get(start++); for (int i = 0; i < cur.neighbors.size(); i++){ UndirectedGraphNode neighbor = cur.neighbors.get(i); if (!map.containsKey(neighbor)){ map.put(neighbor, new UndirectedGraphNode(neighbor.label)); nodes.add(neighbor); } } } // clone neighbors for (int i = 0; i < nodes.size(); i++){ UndirectedGraphNode newNode = map.get(nodes.get(i)); for (int j = 0; j < nodes.get(i).neighbors.size(); j++){ newNode.neighbors.add(map.get(nodes.get(i).neighbors.get(j))); } } return map.get(node); } }
View Code
相关文章推荐
- @Autowired 注释与@Qualifier 注释
- 用“*”画余弦曲线从0度到360度
- matlab linprog函数的使用
- android 签名和混淆打包
- 3GPP TS 24.301 V12.4.0 中文版---4
- C++文件读写
- sql行转列-pivot
- NLP 最近常用分词工具
- java学习_File文件夹遍历
- Eclipse 复制 js 代码卡顿
- Cosmos OpenSSD--greedy_ftl1.2.0(一)
- chrome控制台支持多行js模式
- 纯JS+MVC 打造Web实时聊天室
- Hello,Algorithm!(你好,算法!)
- 机房收费系统----状态图
- 活动目录中的管理工具
- SQL中round()函数、Ucase()、Lcase()、as的用法
- MySQL Replication, 主从和双主配置
- 解读:在命令情况下使用Android NDK交叉编译工具
- Leetcode 199 Binary Tree Right Side View 二叉树右视图