Two questions come up again and again with graphs. Does it contain a cycle? A cycle in a list of course prerequisites means no valid order exists, and a cycle in a dependency list can make a program wait forever. And can its vertices be split into two groups so that every edge goes between the groups? Such a graph is bipartite, which models students and courses, workers and jobs, or two-colouring a map. This lesson answers both with depth-first and breadth-first search in C.
In this lesson you will learn
- Detecting cycles in directed graphs with three colours
- Printing the cycle that was found
- Detecting cycles in undirected graphs using the parent vertex
- Checking whether a graph is bipartite with BFS two-colouring
- Why a graph is bipartite exactly when it has no odd cycle
You should know BFS and DFS. Cycle detection is closely linked to topological sort.
Cycles in Directed Graphs
#include <stdio.h>
#define MAXV 8
/* Directed graph: cycle detection with three colours.
WHITE = not visited, GREY = on the current DFS path, BLACK = finished. */
enum { WHITE, GREY, BLACK };
static int adj[MAXV][MAXV], n;
static int colour[MAXV], parent[MAXV];
static int dfs(int u, int *cycle_start, int *cycle_end) {
colour[u] = GREY;
for (int v = 0; v < n; v++) {
if (!adj[u][v]) continue;
if (colour[v] == GREY) { /* edge back into the current path: a cycle */
*cycle_start = v; *cycle_end = u;
return 1;
}
if (colour[v] == WHITE) {
parent[v] = u;
if (dfs(v, cycle_start, cycle_end)) return 1;
}
}
colour[u] = BLACK;
return 0;
}
static void check(const char *name, int edges[][2], int m, int vertices) {
n = vertices;
for (int i = 0; i < n; i++) {
colour[i] = WHITE; parent[i] = -1;
for (int j = 0; j < n; j++) adj[i][j] = 0;
}
for (int i = 0; i < m; i++) adj[edges[i][0]][edges[i][1]] = 1;
int s = -1, e = -1, found = 0;
for (int u = 0; u < n && !found; u++)
if (colour[u] == WHITE) found = dfs(u, &s, &e);
if (!found) { printf("%s: no cycle\n", name); return; }
int path[MAXV], len = 0;
for (int v = e; v != s; v = parent[v]) path[len++] = v; /* walk back along the path */
path[len++] = s;
printf("%s: cycle", name);
for (int i = len - 1; i >= 0; i--) printf(" %d ->", path[i]);
printf(" %d\n", s);
}
int main(void) {
/* Course prerequisites: an edge a -> b means "a must come before b" */
int ok[][2] = { {0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4} };
int bad[][2] = { {0, 1}, {1, 2}, {2, 3}, {3, 1}, {3, 4} };
check("plan A", ok, 5, 5);
check("plan B", bad, 5, 5);
return 0;
}
Output
plan A: no cycle
plan B: cycle 1 -> 2 -> 3 -> 1
- Each vertex has a colour: white (not visited yet), grey (being explored: it is on the current DFS path) or black (finished, with everything reachable from it explored).
- An edge to a grey vertex points back into the current path, so following the path and then that edge returns to where it started: a cycle.
- An edge to a black vertex is fine. That vertex was fully explored without finding a way back, as when two courses both lead to course 3 in plan A.
- The
parentarray records how DFS reached each vertex, so walking back from the end of the back edge to its target prints the cycle: 1 → 2 → 3 → 1. - Plan B has no valid study order, because courses 1, 2 and 3 each require another of them first.
- The outer loop starts DFS from every white vertex, so parts of the graph that cannot be reached from vertex 0 are checked too. Each vertex and edge is processed once: O(V + E) with adjacency lists (this example uses a small matrix for clarity).
Undirected Cycles and Bipartite Graphs
#include <stdio.h>
#define MAXV 8
static int adj[MAXV][MAXV], n;
/* Undirected graph: a cycle exists if DFS meets a visited vertex that is not its parent */
static int visited[MAXV];
static int has_cycle_from(int u, int parent) {
visited[u] = 1;
for (int v = 0; v < n; v++) {
if (!adj[u][v]) continue;
if (!visited[v]) { if (has_cycle_from(v, u)) return 1; }
else if (v != parent) return 1;
}
return 0;
}
/* Bipartite check: colour with BFS using two colours; neighbours must differ */
static int is_bipartite(int side[]) {
int queue[MAXV];
for (int i = 0; i < n; i++) side[i] = -1;
for (int s = 0; s < n; s++) {
if (side[s] != -1) continue;
int head = 0, tail = 0;
side[s] = 0;
queue[tail++] = s;
while (head < tail) {
int u = queue[head++];
for (int v = 0; v < n; v++) {
if (!adj[u][v]) continue;
if (side[v] == -1) { side[v] = 1 - side[u]; queue[tail++] = v; }
else if (side[v] == side[u]) return 0; /* same colour on both ends */
}
}
}
return 1;
}
static void load(int edges[][2], int m, int vertices) {
n = vertices;
for (int i = 0; i < n; i++) { visited[i] = 0; for (int j = 0; j < n; j++) adj[i][j] = 0; }
for (int i = 0; i < m; i++) adj[edges[i][0]][edges[i][1]] = adj[edges[i][1]][edges[i][0]] = 1;
}
static void report(const char *name, int edges[][2], int m, int vertices) {
load(edges, m, vertices);
int cycle = 0;
for (int u = 0; u < n && !cycle; u++)
if (!visited[u]) cycle = has_cycle_from(u, -1);
int side[MAXV];
int bip = is_bipartite(side);
printf("%s: cycle %s, bipartite %s", name, cycle ? "yes" : "no", bip ? "yes" : "no");
if (bip) {
printf(" (group 0:");
for (int i = 0; i < n; i++) if (side[i] == 0) printf(" %d", i);
printf(" | group 1:");
for (int i = 0; i < n; i++) if (side[i] == 1) printf(" %d", i);
printf(")");
}
printf("\n");
}
int main(void) {
int tree[][2] = { {0, 1}, {0, 2}, {1, 3}, {1, 4} };
int square[][2] = { {0, 1}, {1, 2}, {2, 3}, {3, 0} };
int triangle[][2] = { {0, 1}, {1, 2}, {2, 0} };
report("tree ", tree, 4, 5);
report("square ", square, 4, 4);
report("triangle", triangle, 3, 3);
return 0;
}
Output
tree : cycle no, bipartite yes (group 0: 0 3 4 | group 1: 1 2)
square : cycle yes, bipartite yes (group 0: 0 2 | group 1: 1 3)
triangle: cycle yes, bipartite no
- In an undirected graph every edge works both ways, so the edge back to the vertex you just came from is not a cycle. DFS passes the
parentalong and reports a cycle only when it meets an already visited vertex other than the parent. - The tree has no cycle; the square and the triangle each have one. The union-find structure offers another way to detect undirected cycles.
is_bipartitecolours the start vertex 0 and gives every neighbour the opposite colour, level by level with BFS. If an edge ever joins two vertices of the same colour, the graph cannot be split.- A graph is bipartite exactly when it has no cycle of odd length. The square’s cycle has 4 edges, so it splits into {0, 2} and {1, 3}. The triangle’s cycle has 3, so it is not bipartite.
- Every tree is bipartite: colour the levels alternately.
Which Check Does What
| Graph | Question | Method | Cycle or conflict when |
|---|---|---|---|
| Directed | Is there a cycle? | DFS with white/grey/black | An edge reaches a grey vertex |
| Directed | Is there a cycle? | Kahn’s topological sort | Not all vertices get ordered |
| Undirected | Is there a cycle? | DFS with parent | A visited non-parent neighbour |
| Undirected | Is there a cycle? | Union-find | Both ends already in one set |
| Undirected | Is it bipartite? | BFS or DFS two-colouring | Both ends get the same colour |
Common Mistakes
- Using a simple visited flag for directed graphs. Reaching a black vertex is not a cycle; you need the grey state.
- Treating the parent edge as a cycle in undirected graphs.
- Checking only from vertex 0, which misses disconnected parts.
- Deep recursion on huge graphs, which can overflow the call stack; use an explicit stack or BFS.
Practice Exercises
Exercise 1. Is a cycle with 6 vertices bipartite? What about one with 5?
Show answer
A 6-cycle is bipartite (even length: colours alternate perfectly). A 5-cycle is not (odd length: the last vertex clashes with the first).
Exercise 2. Eight students must be split into two teams so that pairs who dislike each other are in different teams. How can you check whether this is possible?
Show answer
Make each student a vertex and each “dislikes” pair an edge, then run the bipartite check. If it succeeds, the two colours are the two teams.
Frequently Asked Questions
How is cycle detection related to topological sort?
A directed graph has a topological order exactly when it has no cycle. Kahn’s algorithm finds an order by removing vertices with no incoming edges; if some vertices are never removed, they are part of or blocked by a cycle.
What can bipartite graphs be used for?
Matching problems: assigning workers to jobs, students to project slots, or applicants to positions. Algorithms such as Hopcroft-Karp find the largest possible matching in a bipartite graph.
Summary
- Directed cycle: DFS finds an edge to a grey vertex on the current path.
- Undirected cycle: DFS meets a visited vertex that is not its parent.
- Bipartite: two-colour with BFS; a clash means an odd cycle.
- All of these run in O(V + E) with adjacency lists.
