Loading

[Python手撕]判断二分图

class Solution:
    def isBipartite(self, graph: List[List[int]]) -> bool:
        n = len(graph)
        colors = [0]*n

        def bfs(i):
            colors[i] = 1
            queue = [(i,1)]

            while queue:
                node,color = queue.pop(0)

                for next in graph[node]:
                    if colors[next] != 0 and colors[next] == color:
                        return False
                    else:
                        if colors[next] == 0:
                            if color == 1:
                                colors[next] = -1
                                queue.append((next,-1))
                            elif color == -1:
                                colors[next] = 1
                                queue.append((next,1))
            return True

        for i in range(n):
            if colors[i] == 0:
                if not bfs(i):
                    return False
        return True
posted @ 2024-10-05 11:11  Duancf  阅读(19)  评论(0)    收藏  举报