今天做lintcode的图题,第一道就碰到了当时春哥和我给老师跑仿真时候做的东西,那时候根本不懂BFS和DFS,春哥写的代码根本看不懂,还理不清头绪,春哥一行一行给讲解,现在今天又看到了相关的东西,感觉不胜唏嘘啊,感谢当年指导我的各位师兄们。
题目来源是http://www.lintcode.com/zh-cn/problem/clone-graph/
一.目的:给定一种无向图的定义,进行图的复制。
二.思路:
这道题考察对图的遍历和利用HashMap拷贝的方法。
对图的遍历就是两个经典的方法DFS和BFS。BFS经常用Queue实现,DFS经常用递归实现(可改为栈实现)。
拷贝方法是用用HashMap,key存原始值,value存copy的值,用DFS,BFS方法遍历帮助拷贝neighbors的值。
方法一:
1.先使用BFS 遍历每个节点并存至ArrayList;
2.使用HashMap 保存每个节点;
3.使用HashMap保存每个节点的邻居节点。
代码如下:
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return node;
}
// use bfs algorithm to traverse the graph and get all nodes.
ArrayList<UndirectedGraphNode> nodes = getNodes(node);
// copy nodes, store the old->new mapping information in a hash map
HashMap<UndirectedGraphNode, UndirectedGraphNode> mapping = new HashMap<>();
for (UndirectedGraphNode n : nodes) {
mapping.put(n, new UndirectedGraphNode(n.label));
}
// copy neighbors(edges)
for (UndirectedGraphNode n : nodes) {
UndirectedGraphNode newNode = mapping.get(n);
for (UndirectedGraphNode neighbor : n.neighbors) {
UndirectedGraphNode newNeighbor = mapping.get(neighbor);
newNode.neighbors.add(newNeighbor);
}
}
return mapping.get(node);
}
private ArrayList<UndirectedGraphNode> getNodes(UndirectedGraphNode node) {
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
HashSet<UndirectedGraphNode> set = new HashSet<>();
queue.offer(node);
set.add(node);
while (!queue.isEmpty()) {
UndirectedGraphNode head = queue.poll();
for (UndirectedGraphNode neighbor : head.neighbors) {
if(!set.contains(neighbor)){
set.add(neighbor);
queue.offer(neighbor);
}
}
}
return new ArrayList<UndirectedGraphNode>(set);
}
}
这里有个类似的方法,是将复制节点放至图的遍历中,各有优劣,这时候比较需要的方法取之即可。
原文如下:http://www.tuicool.com/articles/a6j2qa
递归DFS和非递归DFS见后文