forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
34 lines (32 loc) · 1.09 KB
/
Solution.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
using System.Collections.Generic;
public class Solution {
public Node CloneGraph(Node node) {
if (node == null) return null;
var dict = new Dictionary<int, Node>();
var queue = new Queue<Node>();
queue.Enqueue(CloneVal(node));
dict.Add(node.val, queue.Peek());
while (queue.Count > 0)
{
var current = queue.Dequeue();
var newNeighbors = new List<Node>(current.neighbors.Count);
foreach (var oldNeighbor in current.neighbors)
{
Node newNeighbor;
if (!dict.TryGetValue(oldNeighbor.val, out newNeighbor))
{
newNeighbor = CloneVal(oldNeighbor);
queue.Enqueue(newNeighbor);
dict.Add(newNeighbor.val, newNeighbor);
}
newNeighbors.Add(newNeighbor);
}
current.neighbors = newNeighbors;
}
return dict[node.val];
}
private Node CloneVal(Node node)
{
return new Node(node.val, new List<Node>(node.neighbors));
}
}