-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution133.cs
89 lines (74 loc) · 2.65 KB
/
Solution133.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution133
{
/// <summary>
/// 133. Clone Graph
/// <a href="https://leetcode.com/problems/clone-graph">See the problem</a>
/// </summary>
public Node CloneGraph(Node node)
{
if (node is null)
{
return null;
}
// Dictionary to keep track of cloned nodes
var clones = new Dictionary<Node, Node>
{
// Initialize the dictionary with the first node
[node] = new(node.val)
};
// Stack for DFS traversal
var stack = new Stack<Node>();
stack.Push(node);
while (stack.Count > 0)
{
var curr = stack.Pop();
// Iterate through all neighbors of the current node
foreach (var neighbor in curr.neighbors)
{
// If the neighbor hasn't been cloned yet
if (!clones.ContainsKey(neighbor))
{
clones[neighbor] = new Node(neighbor.val); // Clone the neighbor and add it to the dictionary
stack.Push(neighbor); // Push the neighbor onto the stack for further traversal
}
// Add the cloned neighbor to the current node's clone's neighbors list
clones[curr].neighbors.Add(clones[neighbor]);
}
}
return clones[node];
}
public Node CloneGraph2(Node node)
{
if (node is null)
{
return null;
}
// Dictionary to keep track of cloned nodes
var clones = new Dictionary<Node, Node>
{
[node] = new(node.val) // Initialize the dictionary with the first node's clone
};
// Queue for BFS traversal
var queue = new Queue<Node>();
queue.Enqueue(node);
while (queue.Count > 0)
{
var curr = queue.Dequeue();
// Iterate through all neighbors of the current node
foreach (var neighbor in curr.neighbors)
{
// If the neighbor hasn't been cloned yet
if (!clones.ContainsKey(neighbor))
{
clones[neighbor] = new Node(neighbor.val); // Clone the neighbor and add it to the dictionary
queue.Enqueue(neighbor); // Enqueue the neighbor onto the queue for further traversal
}
// Add the cloned neighbor to the current node's clone's neighbors list
clones[curr].neighbors.Add(clones[neighbor]);
}
}
return clones[node];
}
}