
Problem
Solution
Submissions
Clone a Directed Graph
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 12
Write a C# program to clone a directed graph. The input graph is represented by a list of nodes, where each node contains a value and a list of its neighbors. Return 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 has neighbors: Node 2 and Node 4
- Node 2 has neighbors: Node 1 and Node 3
- Node 3 has neighbors: Node 2 and Node 4
- Node 4 has neighbors: Node 1 and Node 3
- The returned graph has the same structure.
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(|V| + |E|) where |V| is the number of vertices and |E| is the number of edges
- Space Complexity: O(|V|) for storing the visited nodes
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 depth-first search (DFS) or breadth-first search (BFS) to traverse the graph.
- Keep a mapping between original nodes and cloned nodes to avoid duplicate cloning.
- For each original node, create a corresponding clone node if it doesn't exist.
- For each neighbor of the original node, create a clone if it doesn't exist and add it to the current clone's neighbors.
- Return the clone of the provided node.