package problems.geeks.graph;
/**
* Clone Graph - DFS
*/
import java.util.*;
import adt.graph.GraphNode;
public class Q003A_Clone_Graph_DFS {
public static void main(String[] args) {
GraphNode n0 = new GraphNode(0);
GraphNode n1 = new GraphNode(1);
GraphNode n2 = new GraphNode(2);
GraphNode n3 = new GraphNode(3);
GraphNode n4 = new GraphNode(4);
GraphNode n5 = new GraphNode(5);
GraphNode n6 = new GraphNode(6);
GraphNode n7 = new GraphNode(7);
GraphNode n8 = new GraphNode(8);
n0.addNeighbors(new GraphNode[]{n1, n7});
n1.addNeighbors(new GraphNode[]{n0, n2, n7});
n2.addNeighbors(new GraphNode[]{n1, n3, n5, n8});
n3.addNeighbors(new GraphNode[]{n2, n4, n5});
n4.addNeighbors(new GraphNode[]{n3, n5});
n5.addNeighbors(new GraphNode[]{n2, n3, n4, n6});
n6.addNeighbors(new GraphNode[]{n5, n7, n8});
n7.addNeighbors(new GraphNode[]{n0, n1, n6, n8});
n8.addNeighbors(new GraphNode[]{n2, n6, n7});
n0.printDFS();
GraphNode copy1 = cloneGraph(n0, new HashMap<GraphNode, GraphNode>());
copy1.printDFS();
GraphNode copy2 = cloneGraph(n0);
copy2.printDFS();
}
// ----------------------------------
// Clone graph - DFS recursion
// ----------------------------------
static GraphNode cloneGraph(GraphNode node, Map<GraphNode, GraphNode> map) {
if (node == null) {
return null;
}
GraphNode copy;
// 如果这个节点还没被克隆,克隆它!
if (!map.containsKey(node)) {
copy = new GraphNode(node.index);
map.put(node, copy);
}
else {
copy = map.get(node);
}
for (int i = 0; i < node.neighbors.size(); i++) {
GraphNode neighbor = node.neighbors.get(i);
if (!map.containsKey(neighbor)) {
cloneGraph(neighbor, map);
}
copy.neighbors.add(map.get(neighbor));
}
return copy;
}
// ----------------------------------
// Clone graph - DFS non recursion
// ----------------------------------
static GraphNode cloneGraph(GraphNode node) {
if (node == null) {
return null;
}
// use a hashmap to mark cloned nodes
// map里表示,某个点已经被克隆,并且它的相邻节点也都被克隆
Map<GraphNode, GraphNode> map = new HashMap<GraphNode, GraphNode>();
Stack<GraphNode> stack = new Stack<GraphNode>();
stack.push(node);
while (!stack.isEmpty()) {
GraphNode curr = stack.pop();
GraphNode copy;
// 当前节点已经被克隆了
if (map.containsKey(curr)) {
copy = map.get(curr);
}
// 否则,克隆当前节点
else {
copy = new GraphNode(curr.index);
map.put(curr, copy);
}
for (int i = 0; i < curr.neighbors.size(); i++) {
GraphNode neighbor = curr.neighbors.get(i);
if (!map.containsKey(neighbor)) {
GraphNode neighbor_copy = new GraphNode(neighbor.index);
map.put(neighbor, neighbor_copy);
stack.push(neighbor);
}
copy.neighbors.add(map.get(neighbor));
}
}
return map.get(node);
}
}