forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsonjh1217.swift
More file actions
39 lines (36 loc) · 1.02 KB
/
sonjh1217.swift
File metadata and controls
39 lines (36 loc) · 1.02 KB
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
/**
* 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 {
// O(V+E) time / O(V) space
func cloneGraph(_ node: Node?) -> Node? {
guard let node = node else {
return nil
}
var newNodeByVal = [Int: Node]()
return copy(node: node, newNodeByVal: &newNodeByVal)
}
func copy(node: Node, newNodeByVal: inout [Int: Node]) -> Node {
if let node = newNodeByVal[node.val] {
return node
}
var newNode = Node(node.val)
newNodeByVal[node.val] = newNode
for neighbor in node.neighbors {
guard let neighbor = neighbor else {
continue
}
let newNeighbor = copy(node: neighbor, newNodeByVal: &newNodeByVal)
newNode.neighbors.append(newNeighbor)
}
return newNode
}
}