Skip to content

Commit 7dcd690

Browse files
committed
feat: Add solution for LeetCode problem 261
1 parent 42c41cd commit 7dcd690

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

graph-valid-tree/WhiteHyun.swift

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

0 commit comments

Comments
 (0)