如果 v 被染色,并且颜色与 u 相同,那么说明给定的无向图不是二分图。我们可以直接退出遍历并返回 False 作为答案。
当遍历结束时,说明给定的无向图是二分图,返回 True 作为答案。
深度优先搜索或广度优先搜索对, 都是使用这个思路.
DFS的代码:
classSolution:defisBipartite(self,graph: List[List[int]]) ->bool: n =len(graph) UNCOLORED, RED, GREEN =0,1,2 colors = [UNCOLORED] * ndefdfs(node,color):""" code: 当前结点 color: 当前结点应染颜色 """ colors[node]= color color_next = GREEN if color == RED else REDfor neighbor in graph[node]:if colors[neighbor]== UNCOLORED:ifnotdfs(neighbor, color_next):returnFalseelif colors[neighbor]!= color_next:returnFalsereturnTruefor i inrange(n):if colors[i]== UNCOLORED:ifnotdfs(i, RED):returnFalsereturnTrue
BFS
借助队列实现.
classSolution:defisBipartite(self,graph: List[List[int]]) ->bool: n =len(graph) UNCOLORED, RED, GREEN =0,1,2 colors = [UNCOLORED] * n q = collections.deque()for i inrange(n):if colors[i]== UNCOLORED: q.append(i) colors[i]= REDwhile q: node = q.popleft() color_neighbor = GREEN if colors[node]== RED else REDfor neighbor in graph[node]:if colors[neighbor]== UNCOLORED: colors[neighbor]= color_neighbor q.append(neighbor)elif colors[neighbor]!= color_neighbor:returnFalsereturnTrue