Skip to content

Commit ef969af

Browse files
committed
add solution: graph-valid-tree
1 parent 5180d39 commit ef969af

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

graph-valid-tree/dusunax.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
'''
2+
# 261. Graph Valid Tree
3+
4+
## What constitutes a 🌲
5+
1. it's a graph.
6+
2. Connected: edges == n - 1, visited node count == n
7+
3. Acyclic: there is no cycle.
8+
9+
## Approach A. DFS
10+
use DFS to check if there is a cycle in the graph.
11+
- if there were no cycle & visited node count == n, return True.
12+
13+
## Approach B. Disjoint Set Union (서로소 집합)
14+
use Disjoint Set Union to check if there is a cycle in the graph.
15+
- if you find a cycle, return False immediately.
16+
- if you find no cycle, return True.
17+
18+
### Union Find Operation
19+
- Find: find the root of a node.
20+
- if the root of two nodes is already the same, there is a cycle.
21+
- Union: connect two nodes.
22+
23+
## Approach Comparison
24+
- **A. DFS**: simple and easy to understand.
25+
- **B. Disjoint Set Union**: quicker to check if there is a cycle. if there were more edges, Union Find would be faster.
26+
'''
27+
class Solution:
28+
def validTreeDFS(self, n: int, edges: List[List[int]]) -> bool:
29+
if len(edges) != n - 1:
30+
return False
31+
32+
graph = [[] for _ in range(n)]
33+
for node, neighbor in edges:
34+
graph[node].append(neighbor)
35+
graph[neighbor].append(node)
36+
37+
visited = set()
38+
def dfs(node):
39+
visited.add(node)
40+
for neighbor in graph[node]:
41+
if neighbor not in visited:
42+
dfs(neighbor)
43+
44+
dfs(0)
45+
return len(visited) == n
46+
47+
def validTreeUnionFind(self, n: int, edges: List[List[int]]) -> bool:
48+
if len(edges) != n - 1:
49+
return False
50+
51+
parent = [i for i in range(n)]
52+
53+
def find(x):
54+
if x == parent[x]:
55+
return x
56+
parent[x] = find(parent[x])
57+
return parent[x]
58+
59+
def union(x, y):
60+
parent[find(x)] = find(y)
61+
62+
for node, neighbor in edges:
63+
if find(node) == find(neighbor):
64+
return False
65+
union(node, neighbor)
66+
67+
return True

0 commit comments

Comments
 (0)