Skip to content

Commit 8e76bd1

Browse files
Add CloneGraph class to clone a graph
Implement a method to create a deep copy of a graph using BFS.
1 parent 2eb7d56 commit 8e76bd1

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Graphs/Problems/CloneGraph.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
// Definition for a Node.
3+
class Node {
4+
public int val;
5+
public List<Node> neighbors;
6+
public Node() {
7+
val = 0;
8+
neighbors = new ArrayList<Node>();
9+
}
10+
public Node(int _val) {
11+
val = _val;
12+
neighbors = new ArrayList<Node>();
13+
}
14+
public Node(int _val, ArrayList<Node> _neighbors) {
15+
val = _val;
16+
neighbors = _neighbors;
17+
}
18+
}
19+
*/
20+
21+
class CloneGraph { //create a deep copy of the given graph
22+
public Node cloneGraph(Node node) {
23+
Queue<Node> q = new LinkedList<>();
24+
25+
if(node == null){
26+
return node;
27+
}
28+
29+
q.add(node);
30+
31+
Map<Node, Node> map = new HashMap<>();
32+
Node current;
33+
34+
Node newNode = new Node();
35+
newNode.val = node.val;
36+
map.put(node, newNode);
37+
38+
while(!q.isEmpty()){
39+
current = q.poll();
40+
Node currentClone = map.get(current);
41+
42+
for(Node neighboringNode : current.neighbors){
43+
if(map.containsKey(neighboringNode)){
44+
currentClone.neighbors.add(map.get(neighboringNode));
45+
}
46+
else{
47+
Node newCloneNeighbor = new Node(neighboringNode.val);
48+
map.put(neighboringNode, newCloneNeighbor);
49+
q.add(neighboringNode);
50+
currentClone.neighbors.add(newCloneNeighbor);
51+
}
52+
}
53+
}
54+
55+
return map.get(node);
56+
}
57+
}

0 commit comments

Comments
 (0)