leetcode 886. 可能的二分法(二分图判定)

 DFS染色判定即可

class Solution:
    def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
        vis =  [-1 for _ in range(n + 1)]
        graph = [[] for _ in range(n + 1)]
        for a, b in dislikes:
            graph[a].append([a, b])
            graph[b].append([b, a])
        
        def DFS(p,u):
            print(u)
            for (u,v) in graph[u]:
                print(u,v)
                if v == p:
                    continue
                if vis[v] != -1 and vis[v] == vis[u]:
                    return False
                elif vis[v] ==-1:
                    vis[v]=vis[u] ^ 1
                    if DFS(u,v)==False:
                        return False
            return True           

        for i in range(1,n + 1):
            if vis[i] == -1:
                vis[i] = 0
                if(DFS(0,i)==False):
                    return False
        return True

你可能感兴趣的:(leetcode刷题,深度优先,算法)