
Problem
Solution
Submissions
Clone a Graph
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to clone an undirected graph. Each node in the graph contains a value and a list of its neighbors. Implement the CloneGraph(Node node)
function that returns a deep copy (clone) of the graph.
Example 1
- Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
- Output: [[2,4],[1,3],[2,4],[1,3]]
- Explanation:
- Node 1's neighbors are nodes 2 and 4.
- Node 2's neighbors are nodes 1 and 3.
- Node 3's neighbors are nodes 2 and 4.
- Node 4's neighbors are nodes 1 and 3.
Example 2
- Input: adjList = [[]]
- Output: [[]]
- Explanation:
- The graph has only one node with no neighbors.
Constraints
- The number of nodes in the graph is in the range [0, 100]
- 1 <= Node.val <= 100
- Node.val is unique for each node
- There are no repeated edges and no self-loops in the graph
- Time Complexity: O(N + E) where N is the number of nodes and E is the number of edges
- Space Complexity: O(N)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a hash map to keep track of nodes that have already been processed
- Apply either BFS or DFS to traverse the graph
- For each node, create a clone and recursively clone its neighbors
- Ensure you handle cycles in the graph correctly
- Return null if the input node is null