File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a Node.
3+ * public class Node {
4+ * public var val: Int
5+ * public var neighbors: [Node?]
6+ * public init(_ val: Int) {
7+ * self.val = val
8+ * self.neighbors = []
9+ * }
10+ * }
11+ */
12+
13+ class Solution {
14+ // O(V+E) time / O(V) space
15+ func cloneGraph( _ node: Node ? ) -> Node ? {
16+ guard let node = node else {
17+ return nil
18+ }
19+ var newNodeByVal = [ Int: Node] ( )
20+ return copy ( node: node, newNodeByVal: & newNodeByVal)
21+ }
22+
23+ func copy( node: Node , newNodeByVal: inout [ Int : Node ] ) -> Node {
24+ if let node = newNodeByVal [ node. val] {
25+ return node
26+ }
27+ var newNode = Node ( node. val)
28+ newNodeByVal [ node. val] = newNode
29+
30+ for neighbor in node. neighbors {
31+ guard let neighbor = neighbor else {
32+ continue
33+ }
34+ let newNeighbor = copy ( node: neighbor, newNodeByVal: & newNodeByVal)
35+ newNode. neighbors. append ( newNeighbor)
36+ }
37+ return newNode
38+ }
39+ }
You can’t perform that action at this time.
0 commit comments