Algo-Sim › Graph Traversal

Is Graph Bipartite?

Medium · Graph Traversal · step through it in Java, Python and C++ on your own input

Can the nodes be split into two groups so every edge crosses between them? BFS 2-colouring: a neighbour with the same colour means no.

Problem

An undirected graph is given as adjacency lists: graph[i] lists the neighbours of node i. Return true if the nodes can be split into two groups so that every edge joins nodes from different groups.

Constraints

Edge cases to test

Follow-up questions

Why does an odd cycle fail?
Colours must alternate along a cycle, which is only possible when its length is even.
What is the union-find alternative?
Union each node’s neighbours together and fail if a node ends in the same set as a neighbour.

Solution

Java

public boolean isBipartite(int[][] graph) {
    int n = graph.length;
    // color: 0 = none yet, 1 = red, -1 = blue
    int[] color = new int[n];
    for (int start = 0; start < n; start++) {
        if (color[start] != 0) continue;
        color[start] = 1;
        Queue<Integer> queue = new ArrayDeque<>();
        queue.offer(start);
        while (!queue.isEmpty()) {
            int node = queue.poll();
            for (int next : graph[node]) {
                if (color[next] == 0) {
                    color[next] = -color[node];
                    queue.offer(next);
                } else if (color[next] == color[node]) {
                    return false;
                }
            }
        }
    }
    return true;
}

Python

from collections import deque


def is_bipartite(graph):
    n = len(graph)
    # color: 0 = none yet, 1 = red, -1 = blue
    color = [0] * n
    for start in range(n):
        if color[start] != 0:
            continue
        color[start] = 1
        queue = deque([start])
        while queue:
            node = queue.popleft()
            for nxt in graph[node]:
                if color[nxt] == 0:
                    color[nxt] = -color[node]
                    queue.append(nxt)
                elif color[nxt] == color[node]:
                    return False
    return True

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isBipartite(vector<vector<int>> &graph) {
        int n = int(graph.size());
        // color: 0 = none yet, 1 = red, -1 = blue
        vector<int> color = vector<int>(n);
        for (int start = 0; start < n; start++) {
            if (color[start] != 0)
                continue;
            color[start] = 1;
            deque<int> queue = {};
            queue.push_back(start);
            while (!queue.empty()) {
                int node = queue.front();
                queue.pop_front();
                for (int next : graph[node]) {
                    if (color[next] == 0) {
                        color[next] = -color[node];
                        queue.push_back(next);
                    } else if (color[next] == color[node]) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
};

More Graph Traversal problems