785. Is Graph Bipartite?
solution
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 Truefollow up
Last updated