-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path0133-CloneGraph.cs
46 lines (38 loc) · 1.24 KB
/
0133-CloneGraph.cs
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
44
45
46
//-----------------------------------------------------------------------------
// Runtime: 248ms
// Memory Usage: 30.9 MB
// Link: https://leetcode.com/submissions/detail/380534574/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0133_CloneGraph
{
public Node CloneGraph(Node node)
{
var map = new Dictionary<int, Node>();
return CloneGraph(node, map);
}
public Node CloneGraph(Node node, IDictionary<int, Node> map)
{
if (node == null) return null;
if (map.ContainsKey(node.val)) return map[node.val];
var newNode = new Node(node.val, new List<Node>());
map.Add(node.val, newNode);
foreach (var child in node.neighbors)
newNode.neighbors.Add(CloneGraph(child, map));
return newNode;
}
public class Node
{
public int val;
public IList<Node> neighbors;
public Node() { }
public Node(int _val, IList<Node> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
}
}
}