Skip to content

Commit d691c5a

Browse files
authored
Create Clone_Graph.java
1 parent d9258bc commit d691c5a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Clone_Graph.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Leetcode 133. Clone Graph
2+
// Question - https://leetcode.com/problems/clone-graph/
3+
4+
/*
5+
// Definition for a Node.
6+
class Node {
7+
public int val;
8+
public List<Node> neighbors;
9+
10+
public Node() {
11+
val = 0;
12+
neighbors = new ArrayList<Node>();
13+
}
14+
15+
public Node(int _val) {
16+
val = _val;
17+
neighbors = new ArrayList<Node>();
18+
}
19+
20+
public Node(int _val, ArrayList<Node> _neighbors) {
21+
val = _val;
22+
neighbors = _neighbors;
23+
}
24+
}
25+
*/
26+
class Solution {
27+
28+
//to keep track of already explored nodes
29+
HashMap<Integer,Node> map = new HashMap<Integer,Node>();
30+
31+
public Node cloneGraph(Node node) {
32+
if(node==null) return null; //empty graph
33+
34+
//if the node is already explored then return the newly created node which is stored in the map
35+
if(map.containsKey(node.val)) return map.get(node.val);
36+
37+
//creating new node from the old node
38+
Node curr = new Node(node.val, new ArrayList<>());
39+
40+
//adding value to the map
41+
//NOTE - the neighbours have not been added yet. This is because if we don't do this step here our code might get stuck in an infite recursion - this will heppen when there is a cycle.
42+
//example - Node 5 is neighbour of Node 6. Node 5 will call clone(Node 6) and Node(Clone 6) will call clone(Node 5) and so on...
43+
//to avoid this as soon as we create a new node of Node 5, we put it's object in our map. When Node 5 call clone(Node 6) and then Node 6 calls clone(Node 5) an object from the map is returned. Preventing code failure.
44+
map.put(node.val,curr);
45+
46+
for(Node neighbor : node.neighbors){
47+
curr.neighbors.add(cloneGraph(neighbor));
48+
}
49+
50+
return curr;
51+
}
52+
}

0 commit comments

Comments
 (0)