DATA STRUCTURES PROGRAM • GRAPHS

Check Whether a Graph Is Bipartite

Learn how to check whether a graph is bipartite using a clear C program.

IntermediateBipartiteTwo-coloringBFS

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Graph is bipartite.

COMPLETE C PROGRAM

Complete C implementation

dsa-bipartite-graph-bfs.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int graph[4][4] = {
        {0,1,0,1}, {1,0,1,0}, {0,1,0,1}, {1,0,1,0}
    };
    int color[4] = {-1,-1,-1,-1}, queue[4], front = 0, rear = 0, valid = 1;
    color[0] = 0; queue[rear++] = 0;
    while (front < rear && valid) {
        int vertex = queue[front++];
        for (int neighbour = 0; neighbour < 4; neighbour++) if (graph[vertex][neighbour]) {
            if (color[neighbour] == -1) {
                color[neighbour] = 1 - color[vertex]; queue[rear++] = neighbour;
            } else if (color[neighbour] == color[vertex]) { valid = 0; break; }
        }
    }
    puts(valid ? "Graph is bipartite." : "Graph is not bipartite.");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Graph is bipartite.
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Assign opposite colors across every edge and reject any same-color adjacency.
  3. Display the computed result.

Assign opposite colors across every edge and reject any same-color adjacency.

EFFICIENCY

Time and space complexity

Time complexity

O(V²) with matrix

Auxiliary space

O(V)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.