File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ //
2
+ // 261. Graph Valid Tree
3
+ // https://leetcode.com/problems/graph-valid-tree/description/
4
+ // Dale-Study
5
+ //
6
+ // Created by WhiteHyun on 2024/07/06.
7
+ //
8
+
9
+ final class Solution {
10
+ func validTree( _ n: Int , _ edges: [ [ Int ] ] ) -> Bool {
11
+ guard edges. count == n - 1
12
+ else {
13
+ return false
14
+ }
15
+
16
+ var dictionary : [ Int : [ Int ] ] = [ : ]
17
+ var visited : Set < Int > = [ ]
18
+
19
+ for edge in edges {
20
+ dictionary [ edge [ 0 ] , default: [ ] ] . append ( edge [ 1 ] )
21
+ dictionary [ edge [ 1 ] , default: [ ] ] . append ( edge [ 0 ] )
22
+ }
23
+
24
+ func dfs( parent: Int , node: Int ) {
25
+ if visited. contains ( node) {
26
+ return
27
+ }
28
+
29
+ visited. insert ( node)
30
+
31
+ if let childNodes = dictionary [ node] {
32
+ for childNode in childNodes where childNode != parent {
33
+ dfs ( parent: node, node: childNode)
34
+ }
35
+ }
36
+ }
37
+
38
+ dfs ( parent: - 1 , node: 0 )
39
+
40
+ return visited. count == n
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments