forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWhiteHyun.swift
More file actions
41 lines (33 loc) ยท 785 Bytes
/
WhiteHyun.swift
File metadata and controls
41 lines (33 loc) ยท 785 Bytes
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
//
// 133. Clone Graph
// https://leetcode.com/problems/clone-graph/description/
// Dale-Study
//
// Created by WhiteHyun on 2024/06/28.
//
/**
* Definition for a Node.
* public class Node {
* public var val: Int
* public var neighbors: [Node?]
* public init(_ val: Int) {
* self.val = val
* self.neighbors = []
* }
* }
*/
class Solution {
var cache: [Int: Node] = [:]
func cloneGraph(_ originalNode: Node?) -> Node? {
guard let originalNode
else {
return nil
}
guard cache[originalNode.val] == nil
else { return cache[originalNode.val]! }
let node = Node(originalNode.val)
cache[originalNode.val] = node
node.neighbors = originalNode.neighbors.map(cloneGraph)
return node
}
}