forked from LeetCode-in-Net/LeetCode-in-Net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
55 lines (47 loc) · 1.43 KB
/
Solution.cs
File metadata and controls
55 lines (47 loc) · 1.43 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
44
45
46
47
48
49
50
51
52
53
54
55
namespace LeetCodeNet.G0101_0200.S0133_clone_graph {
// #Medium #Hash_Table #Depth_First_Search #Breadth_First_Search #Graph #Udemy_Graph
// #Top_Interview_150_Graph_General #2025_07_12_Time_117_ms_(96.34%)_Space_47.31_MB_(97.95%)
using System.Collections.Generic;
/*
// Definition for a Node.
public class Node {
public int val;
public IList<Node> neighbors;
public Node() {
val = 0;
neighbors = new List<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new List<Node>();
}
public Node(int _val, List<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
*/
public class Solution {
public Node CloneGraph(Node node) {
return CloneGraph(node, new Dictionary<Node, Node>());
}
private Node CloneGraph(Node node, Dictionary<Node, Node> processedNodes) {
if (node == null) {
return null;
} else if (processedNodes.ContainsKey(node)) {
return processedNodes[node];
}
Node newNode = new Node();
processedNodes[node] = newNode;
newNode.val = node.val;
newNode.neighbors = new List<Node>();
foreach (Node neighbor in node.neighbors) {
Node clonedNeighbor = CloneGraph(neighbor, processedNodes);
if (clonedNeighbor != null) {
newNode.neighbors.Add(clonedNeighbor);
}
}
return newNode;
}
}
}