2
// Definition for a Node.5
public List<Node> neighbors;8
neighbors = new ArrayList<Node>();10
public Node(int _val) {12
neighbors = new ArrayList<Node>();14
public Node(int _val, ArrayList<Node> _neighbors) {16
neighbors = _neighbors;22
public void dfs(Node node, Node copy, Node[] visited) {24
copy; // store the current node at it's val index which will tell us that this node is now27
// now traverse for the adjacent nodes of root node28
for (Node n : node.neighbors) {29
// check whether that node is visited or not30
// if it is not visited, there must be null31
if (visited[n.val] == null) {32
// so now if it not visited, create a new node33
Node newNode = new Node(n.val);34
// add this node as the neighbor of the prev copied node35
copy.neighbors.add(newNode);36
// make dfs call for this unvisited node to discover whether it's adjacent37
// nodes are explored or not38
dfs(n, newNode, visited);40
// if that node is already visited, retrieve that node from visited array41
// and add it as the adjacent node of prev copied node42
// THIS IS THE POINT WHY WE USED NODE[] INSTEAD OF BOOLEAN[] ARRAY43
copy.neighbors.add(visited[n.val]);48
public Node cloneGraph(Node node) {50
return null; // if the actual node is empty there is nothing to copy, so return null52
new Node(node.val); // create a new node , with same value as the root node(given node)55
[101]; // in this question we will create an array of Node(not boolean) why ? , because56
// i have to add all the adjacent nodes of particular vertex, whether it's57
// visited or not, so in the Node[] initially null is stored, if that node is58
// visited, we will store the respective node at the index, and can retrieve that60
Arrays.fill(visited, null); // initially store null at all places61
dfs(node, copy, visited); // make a dfs call for traversing all the vertices of the root node62
return copy; // in the end return the copy node