1. 程式人生 > 實用技巧 >leetcode-785-判斷二分圖

leetcode-785-判斷二分圖

題目描述:

第一次提交:通過76/78 留坑

class Solution:
    def isBipartite(self, graph: List[List[int]]) -> bool:
        dic = {}
        l = []
        for i in range(len(graph)):
            if graph[i] != []:
                dic[i] = 0
                l.append(i)
                break
        tmp = 1
        while
l: print(l) for i in range(len(l)): for node in graph[l.pop(0)]: if node not in dic: dic[node] = tmp l.append(node) elif dic[node] != tmp: return False tmp
= 0 if tmp == 1 else 1 return True

改:DFS O(N+M) O(N)

class Solution:
    def isBipartite(self, graph) -> bool:
        dye = defaultdict(int)
        def DFS(s, color):
            dye[s] = color
            for i in graph[s]:
                # 已經上色了,如果和我一樣表示不行
                if dye[i] == color:
                    
return False # 沒上色就染成和我相反的 if not dye[i]: if not DFS(i, -color): return False return True for i in range(len(graph)): # 沒被染色的就繼續染色 if not dye[i]: if not DFS(i, 1): return False return True