DATA STRUCTURES PROGRAM • GRAPHS
Check Whether a Graph Is Bipartite
Learn how to check whether a graph is bipartite using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Graph is bipartite.
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Graph is bipartite.
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Assign opposite colors across every edge and reject any same-color adjacency.
- 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.
