A graph isĀ bipartiteĀ if the nodes can be partitioned into two independent setsĀ AĀ andĀ BĀ such thatĀ everyĀ edge in the graph connects a node in setĀ AĀ and a node in setĀ B
def isBipartite(graph):
colors = [0] * len(graph)
def helper(node, color):
nonlocal colors
if colors[node] != 0:
return colors[node] == color
colors[node] = color
for neighbour in graph[node]:
if not helper(neighbour, -color):
return False
return True
for i in range(len(graph)):
if colors[i] == 0 and not helper(i, 1):
return False
return True