【力扣】并查集模板
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
干净清爽,直接放进备忘录
 
                    
                 
                
            
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号