785. Is Graph Bipartite?

https://leetcode.com/problems/is-graph-bipartite/description/

solution

判断二分图问题: 对图中每个点进行染色。二分图左边的部分置为-1,右边部分全部置为1,那么,任意相邻的两点颜色都不一样

  • bfs

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

        for i in range(len(graph)):  # 注意这里每个点都要遍历一次
            if colors[i] != 0:
                continue

            queue = collections.deque()
            queue.append(i)
            colors[i] = 1  # 起始颜色都置为1

            while queue:
                node = queue.popleft()

                for adj in graph[node]:
                    if colors[adj] == colors[node]:
                        return False
                    if colors[adj] == 0:
                        colors[adj] = -colors[node]
                        queue.append(adj)
        return True

时间复杂度:O(∣V∣+∣E∣) 空间复杂度:O(∣V∣)

  • dfs

follow up

1557. Minimum Number of Vertices to Reach All Nodes

886. Possible Bipartition

Last updated