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:
- Initialize the
dparray with zeros. - For each node
i, calculate the number of cyclic paths that start at nodei. - If there are no edges leaving node
i, setdp[i][i] = 1, since a single node is considered a cyclic path. - Otherwise, for each neighbor
jof nodei, add the number of cyclic paths that start at nodeiand end at nodejtodp[i][j]. - For each node
j, calculate the number of cyclic paths that end at nodej. - If there are no edges entering node
j, setdp[j][j] = 1, since a single node is considered a cyclic path. - Otherwise, for each neighbor
iof nodej, add the number of cyclic paths that start at nodeiand end at nodejtodp[j][i]. - 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
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;
}