785. 判断二分图
class IsBipartite:"""判断二分图,dfs、bfs分别实现"""def __init__(self):self.success = Trueself.color = []self.visited = []def dfs(self, graph):n = len(graph)self.color = [False] * nself.visited = [False] * nfor v in range(n):if not self.visited[v]:self.dfs_traverse(graph, v)return self.successdef dfs_traverse(self, graph, v):if not self.success:returnself.visited[v] = Truefor w in graph[v]:if not self.visited[w]:self.color[w] = not self.color[v]self.dfs_traverse(graph, w)else:if self.color[w] == self.color[v]:self.success = Falsereturndef bfs(self, graph):n = len(graph)self.color = [False] * nself.visited = [False] * nfor v in range(n):if not self.visited[v]:self.bfs_traverse(graph, v)return self.successdef bfs_traverse(self, graph, start):self.visited[start] = Truequeue = [start]while queue and self.success:v = queue.pop(0)for w in graph[v]:if not self.visited[w]:self.color[w] = not self.color[v]self.visited[w] = Truequeue.append(w)else:if self.color[w] == self.color[v]:self.success = Falsereturn