forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0133-clone-graph.swift
More file actions
33 lines (28 loc) · 801 Bytes
/
0133-clone-graph.swift
File metadata and controls
33 lines (28 loc) · 801 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
/**
* 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 mapping: [Node?: Node?] = [:]
func cloneGraph(_ node: Node?) -> Node? {
guard let node = node else { return nil }
// check if cache exists
if mapping[node] != nil {
return mapping[node]!
}
// otherwise, create a node, cache it, recurse for children
let newNode = Node(node.val)
mapping[node] = newNode
node.neighbors.forEach { neighbor in
newNode.neighbors.append(cloneGraph(neighbor))
}
return newNode
}
}