DFS

LeetCode 886 Possible Bipartition (Python)

Posted by 小明MaxMing on May 27, 2020

题目

Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size.

Each person may dislike some other people, and they should not go into the same group.

Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.

Return true if and only if it is possible to split everyone into two groups in this way.

解题思路

对每个点进行黑白染色(DFS或BFS),如果发现冲突则返回False

代码

class Solution:
    def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:
        edge = [[] for _ in range(N + 1)]
        for u, v in dislikes:
            edge[u].append(v)
            edge[v].append(u)
        color = [0] * (N + 1)
        for i in range(1, N + 1):
            if color[i] == 0:
                q = [i]
                color[i] = 1
                while q:
                    cur = q.pop()
                    cur_c = color[cur]
                    for node in edge[cur]:
                        if color[node] == 0:
                            color[node] = cur_c * -1
                            q.append(node)
                        elif color[node] == cur_c:
                            return False
        return True

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅