forked from Kyrylo-Ktl/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPossible Bipartition.py
More file actions
38 lines (27 loc) · 926 Bytes
/
Possible Bipartition.py
File metadata and controls
38 lines (27 loc) · 926 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
from collections import defaultdict
from typing import List
class Solution:
"""
Time: O(V+E)
Memory: O(V+E)
"""
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
def dfs(i: int, curr_color: bool) -> bool:
color[i] = curr_color
for j in graph[i]:
if color[j] is curr_color:
return False
if color[j] is None and (not dfs(j, not curr_color)):
return False
return True
if n == 1 or not dislikes:
return True
graph = defaultdict(list)
color = defaultdict(lambda: None)
for u, v in dislikes:
graph[u].append(v)
graph[v].append(u)
for person_id in range(1, n + 1):
if color[person_id] is None and not dfs(person_id, True):
return False
return True