Graph Theory37 sections · 1633 units
Open in Course

LeetCode 785 Is Graph Bipartite? - Implementation

The code

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 00 and 11.

This runs in O(V+E)O(V + E) time and uses O(V)O(V) space.