forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWhiteHyun.swift
More file actions
42 lines (34 loc) · 889 Bytes
/
WhiteHyun.swift
File metadata and controls
42 lines (34 loc) · 889 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
37
38
39
40
41
42
//
// 261. Graph Valid Tree
// https://leetcode.com/problems/graph-valid-tree/description/
// Dale-Study
//
// Created by WhiteHyun on 2024/07/06.
//
final class Solution {
func validTree(_ n: Int, _ edges: [[Int]]) -> Bool {
guard edges.count == n - 1
else {
return false
}
var dictionary: [Int: [Int]] = [:]
var visited: Set<Int> = []
for edge in edges {
dictionary[edge[0], default: []].append(edge[1])
dictionary[edge[1], default: []].append(edge[0])
}
func dfs(parent: Int, node: Int) {
if visited.contains(node) {
return
}
visited.insert(node)
if let childNodes = dictionary[node] {
for childNode in childNodes where childNode != parent {
dfs(parent: node, node: childNode)
}
}
}
dfs(parent: -1, node: 0)
return visited.count == n
}
}