714078. Count Cyclic Paths

Medium

Count Cyclic Paths

Slug: count-cyclic-paths--170647 Difficulty: Medium Id: 714078 Topic Tags: Dynamic Programming, Algorithms Company Tags: OYO Rooms

Summary

The problem involves counting the number of cyclic paths in a given graph. The graph is represented as an adjacency matrix, and each node has a unique value (id). A path is considered cyclic if it starts and ends at the same node.

Detailed Explanation

To solve this problem, we can use dynamic programming to count the number of cyclic paths. We'll create a 2D array dp where dp[i][j] represents the number of cyclic paths that start at node i and end at node j.

Here's the step-by-step approach:

  1. Initialize the dp array with zeros.
  2. For each node i, calculate the number of cyclic paths that start at node i.
  3. If there are no edges leaving node i, set dp[i][i] = 1, since a single node is considered a cyclic path.
  4. Otherwise, for each neighbor j of node i, add the number of cyclic paths that start at node i and end at node j to dp[i][j].
  5. For each node j, calculate the number of cyclic paths that end at node j.
  6. If there are no edges entering node j, set dp[j][j] = 1, since a single node is considered a cyclic path.
  7. Otherwise, for each neighbor i of node j, add the number of cyclic paths that start at node i and end at node j to dp[j][i].
  8. The total count of cyclic paths is the sum of all dp[i][j] values.

Time complexity: O(n^2), where n is the number of nodes in the graph. Space complexity: O(n^2) for the dp array.

Optimized Solutions

Java

View on GeeksforGeeks
public int countCyclicPaths(int[][] graph) {
    int n = graph.length;
    int[][] dp = new int[n][n];
    
    // Calculate number of cyclic paths starting at each node
    for (int i = 0; i < n; i++) {
        if (graph[i].length == 0) {
            dp[i][i] = 1;
        } else {
            for (int j = 0; j < graph[i].length; j++) {
                int neighborId = graph[i][j];
                dp[i][neighborId] += 1;
            }
        }
    }
    
    // Calculate number of cyclic paths ending at each node
    for (int i = 0; i < n; i++) {
        if (graph[i].length == 0) {
            dp[i][i] = 1;
        } else {
            for (int j = 0; j < graph[i].length; j++) {
                int neighborId = graph[i][j];
                dp[neighborId][i] += 1;
            }
        }
    }
    
    // Count total number of cyclic paths
    int count = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            count += dp[i][j];
        }
    }
    
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.