Ques:- Write a function to copy a graph
Right Answer:
```python
class Node:
def __init__(self, val):
self.val = val
self.neighbors = []
def cloneGraph(node):
if not node:
return None
# Dictionary to hold the mapping from original node to its clone
clone_map = {}
def dfs(n):
if n in clone_map:
return clone_map[n]
# Create a clone for the current node
clone = Node(n.val)
clone_map[n] = clone
# Recursively clone the neighbors
for neighbor in n.neighbors:
clone.neighbors.append(dfs(neighbor))
return clone
return dfs(node)
```
```python
class Node:
def __init__(self, val):
self.val = val
self.neighbors = []
def cloneGraph(node):
if not node:
return None
# Dictionary to hold the mapping from original node to its clone
clone_map = {}
def dfs(n):
if n in clone_map:
return clone_map[n]
# Create a clone for the current node
clone = Node(n.val)
clone_map[n] = clone
# Recursively clone the neighbors
for neighbor in n.neighbors:
clone.neighbors.append(dfs(neighbor))
return clone
return dfs(node)
```