Here is the full solution:
function isBipartite(graph):
n := length of graph
color := array of size n, all -1
for i from 0 to n - 1:
if color[i] = -1 then
queue := [i]
color[i] := 0
while queue not empty:
node := queue.pop_front()
for neighbor in graph[node]:
if color[neighbor] = -1 then
color[neighbor] := 1 - color[node]
queue.push(neighbor)
else if color[neighbor] = color[node] then
return false
return true
The trick 1 - color[node] flips between and .
This runs in time and uses space.