Skip to content

Commit f9e94fd

Browse files
committed
feat: Add solution for LeetCode problem 133
1 parent 4a31fd5 commit f9e94fd

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

clone-graph/WhiteHyun.swift

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
//
2+
// 133. Clone Graph
3+
// https://leetcode.com/problems/clone-graph/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/28.
7+
//
8+
9+
/**
10+
* Definition for a Node.
11+
* public class Node {
12+
* public var val: Int
13+
* public var neighbors: [Node?]
14+
* public init(_ val: Int) {
15+
* self.val = val
16+
* self.neighbors = []
17+
* }
18+
* }
19+
*/
20+
21+
class Solution {
22+
var cache: [Int: Node] = [:]
23+
24+
func cloneGraph(_ originalNode: Node?) -> Node? {
25+
guard let originalNode
26+
else {
27+
return nil
28+
}
29+
30+
guard cache[originalNode.val] == nil
31+
else { return cache[originalNode.val]! }
32+
33+
let node = Node(originalNode.val)
34+
cache[originalNode.val] = node
35+
36+
37+
node.neighbors = originalNode.neighbors.map(cloneGraph)
38+
39+
return node
40+
}
41+
}

0 commit comments

Comments
 (0)