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
36 lines (28 loc) · 985 Bytes
/
sonjh1217.swift
File metadata and controls
36 lines (28 loc) · 985 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
import Foundation
class Solution {
// O(n) time / O(n) space
func validTree(_ n: Int, _ edges: [[Int]]) -> Bool {
guard edges.count == n - 1 else {
return false
}
var connectedNodes = Array(repeating: [Int](), count: n)
for edge in edges {
connectedNodes[edge[0]].append(edge[1])
connectedNodes[edge[1]].append(edge[0])
}
var isVisiteds = Array(repeating: false, count: n)
var head = 0
var queue = [0]
isVisiteds[0] = true
while head < queue.count {
let currentNode = queue[head]
head += 1
for node in connectedNodes[currentNode] {
guard !isVisiteds[node] else { continue }
isVisiteds[node] = true
queue.append(node)
}
}
return isVisiteds.allSatisfy { $0 }
}
}