Skip to content

How to Fix Graph Cycle Detection and Infinite Loop Errors

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix Graph Cycle Detection and Infinite Loop Errors. We cover key concepts, practical examples, and best practices.

Graph cycle detection errors occur when DFS or BFS traversals do not track visited nodes, or when directed graph cycle detection uses the wrong method (parent tracking instead of recursion stack), causing infinite loops or incorrect results.

Quick Fix

Wrong

void dfs(const Graph& g, int node) {
    std::cout << node << " ";
    for (int neighbor : g.neighbors(node)) {
        dfs(g, neighbor);  // infinite loop on cycles
    }
}

For a graph with a cycle (1-2-3-1), this recurses infinitely.

void dfs(const Graph& g, int node, std::vector<bool>& visited) {
    if (visited[node]) return;
    visited[node] = true;
    std::cout << node << " ";
    for (int neighbor : g.neighbors(node)) {
        dfs(g, neighbor, visited);
    }
}
1 2 3 4 5

Fix for directed graph cycles

bool hasCycle(const Graph& g) {
    enum State { UNVISITED, VISITING, VISITED };
    std::vector<State> state(g.size(), UNVISITED);

    std::function<bool(int)> dfs = [&](int node) {
        if (state[node] == VISITING) return true;  // cycle!
        if (state[node] == VISITED) return false;
        state[node] = VISITING;
        for (int neighbor : g.neighbors(node)) {
            if (dfs(neighbor)) return true;
        }
        state[node] = VISITED;
        return false;
    };

    for (int i = 0; i < g.size(); ++i) {
        if (dfs(i)) return true;
    }
    return false;
}

Fix for undirected graph cycles

bool hasCycleUndirected(const Graph& g) {
    std::vector<bool> visited(g.size(), false);

    std::function<bool(int, int)> dfs = [&](int node, int parent) {
        visited[node] = true;
        for (int neighbor : g.neighbors(node)) {
            if (!visited[neighbor]) {
                if (dfs(neighbor, node)) return true;
            } else if (neighbor != parent) {
                return true;  // cycle detected
            }
        }
        return false;
    };

    for (int i = 0; i < g.size(); ++i) {
        if (!visited[i] && dfs(i, -1)) return true;
    }
    return false;
}

Prevention

  • Always track visited nodes in graph traversals.
  • Use 3-state coloring for directed graph cycle detection.
  • Track parent node for undirected graph cycle detection.
  • Use union-find (DSU) for cycle detection in undirected graphs without DFS.
  • Test with both cyclic and acyclic graphs.

DodaTech Tools

Doda Browser's graph visualizer animates traversal paths and highlights cycle detection. DodaZIP archives graph topology data. Durga Antivirus Pro detects infinite loop patterns from missing visited checks.

Common Mistakes with graph cycle detection

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world DS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

Why does cycle detection differ between directed and undirected graphs?

In undirected graphs, an edge to a visited node is only a cycle if it is not the parent node. In directed graphs, an edge to any node currently on the recursion stack indicates a cycle, because the edge direction matters.

What is the difference between DFS coloring and simple visited tracking?

Simple visited tracking prevents revisiting nodes but cannot distinguish between back edges (cycles) and cross edges (non-cycles) in directed graphs. Three-state coloring (UNVISITED, VISITING, VISITED) identifies back edges specifically.

Can I detect cycles without recursion?

Yes, use Kahn's algorithm (topological sort with indegree) for directed graphs or union-find for undirected graphs. These avoid recursion depth issues.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro