Harukaze

 

【力扣】并查集模板

 1 class Solution:
 2     def isBipartite(self, graph: List[List[int]]) -> bool:
 3         n=len(graph)
 4         boss=[i for i in range(n)]
 5 
 6         def find(x):
 7             nonlocal boss
 8             if boss[x]!=x:
 9                 boss[x]=find(boss[x])
10             return boss[x]
11         def merge(x,y):
12             bx=find(x)
13             by=find(y)
14             boss[bx]=by
15 
16         for i, e in enumerate(graph):
17             fi=find(i)
18             for j in e:
19                 if find(j)==fi:
20                     return False
21             if e:
22                 b=e[0]
23                 for j in e[1:]:
24                     merge(b,j)
25         return True

干净清爽,直接放进备忘录

posted on 2021-09-16 10:31  Harukaze  阅读(56)  评论(0)    收藏  举报

导航