generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem26.cs
More file actions
43 lines (36 loc) · 1.08 KB
/
Problem26.cs
File metadata and controls
43 lines (36 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/clone-graph/">Clone Graph</see>.
/// </summary>
public static class Problem26
{
/// <summary>
/// Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="node">Graph node.</param>
/// <returns>Cloned graph.</returns>
public static GraphNode? CloneGraph(GraphNode? node)
{
if (node == null)
{
return null;
}
return Traverse(node, new Dictionary<int, GraphNode>());
}
private static GraphNode Traverse(GraphNode node, IDictionary<int, GraphNode> dict)
{
if (dict.ContainsKey(node.Val))
{
return dict[node.Val];
}
var newNode = new GraphNode(node.Val);
dict.Add(node.Val, newNode);
foreach (var neighbour in node.Neighbors)
{
newNode.Neighbors.Add(Traverse(neighbour, dict));
}
return newNode;
}
}