From 707c0cd33a76f9b395b4827e11e24182cb727af1 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 22 Jun 2024 10:39:31 +0800 Subject: [PATCH] 20240622 Finished --- LeetCodeSharp/Problems/Solution133.cs | 91 +++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 LeetCodeSharp/Problems/Solution133.cs diff --git a/LeetCodeSharp/Problems/Solution133.cs b/LeetCodeSharp/Problems/Solution133.cs new file mode 100644 index 0000000..d5ab37f --- /dev/null +++ b/LeetCodeSharp/Problems/Solution133.cs @@ -0,0 +1,91 @@ +// [133] Clone Graph + + +using System.Collections.Generic; + +namespace LeetCodeSharp.Problems133 +{ + // Submission codes start here + + public class Node + { + public int val; + public IList neighbors; + + public Node() + { + val = 0; + neighbors = new List(); + } + + public Node(int _val) + { + val = _val; + neighbors = new List(); + } + + public Node(int _val, List _neighbors) + { + val = _val; + neighbors = _neighbors; + } + } + + public class Solution + { + private readonly HashSet _visited = new HashSet(); + + public Node CloneGraph(Node node) + { + if (node == null) + { + return null; + } + + var map = new Dictionary(); + + _visited.Clear(); + FindAllNode(map, node); + _visited.Clear(); + ReplaceAllNode(map, node); + + return map[node.val]; + } + + private void FindAllNode(Dictionary map, Node node) + { + if (_visited.Contains(node.val)) + { + return; + } + + _visited.Add(node.val); + map[node.val] = new Node(node.val); + + foreach (var neighbor in node.neighbors) + { + map[neighbor.val] = new Node(neighbor.val); + FindAllNode(map, neighbor); + } + } + + private void ReplaceAllNode(Dictionary map, Node node) + { + if (_visited.Contains(node.val)) + { + return; + } + + _visited.Add(node.val); + var newNode = map[node.val]; + + foreach (var neighbor in node.neighbors) + { + newNode.neighbors.Add(map[neighbor.val]); + ReplaceAllNode(map, neighbor); + } + } + } + + // Submission codes end here +} \ No newline at end of file