-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloneGraph
60 lines (39 loc) · 1.31 KB
/
CloneGraph
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/***************************************************************************
Class for graph node is as follows:
class graphNode {
public int data;
public ArrayList<graphNode> neighbours;
graphNode() {
data = 0;
neighbours = new ArrayList<graphNode>();
}
graphNode(int val) {
data = val;
neighbours = new ArrayList<graphNode>();
}
graphNode(int val, ArrayList<graphNode> neighbours) {
data = val;
this.neighbours = neighbours;
}
}
******************************************************************************/
import java.util.*;
public class Solution {
public static graphNode cloneGraph(graphNode node) {
return cloneGraphDFSHelper(node,new HashMap<graphNode,graphNode>());
}
private static graphNode cloneGraphDFSHelper(graphNode cur, HashMap<graphNode, graphNode> visited) {
if (cur == null) {
return null;
}
if (visited.containsKey(cur)) {
return visited.get(cur);
}
graphNode newNode = new graphNode(cur.data);
visited.put(cur, newNode);
for (graphNode n : cur.neighbours) {
newNode.neighbours.add(cloneGraphDFSHelper(n, visited));
}
return newNode;
}
}