forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelight010.swift
More file actions
34 lines (26 loc) · 1.01 KB
/
delight010.swift
File metadata and controls
34 lines (26 loc) · 1.01 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
class Solution {
// Time O(V+E)
// Space O(V)
func cloneGraph(_ node: Node?) -> Node? {
guard let node = node else { return nil }
var visited: [Int: Node] = [:]
var queue: [Node] = []
let firstNode = Node(node.val)
visited[node.val] = firstNode
queue.append(node)
while !queue.isEmpty {
let currentNode = queue.removeFirst()
for neighbor in currentNode.neighbors {
guard let neighbor = neighbor else { continue }
if let clonedNeighbor = visited[neighbor.val] {
visited[currentNode.val]!.neighbors.append(clonedNeighbor)
} else {
visited[neighbor.val] = Node(neighbor.val)
visited[currentNode.val]!.neighbors.append(visited[neighbor.val])
queue.append(neighbor)
}
}
}
return firstNode
}
}