1. Introduction
A graph is a data structure consisting of vertices (nodes) and edges (connections between nodes).
In a directed graph, every edge has a specific direction. For example, an edge 0 → 1 means we can travel from vertex 0 to vertex 1, but it does not mean we can travel from vertex 1 to vertex 0.
A cycle occurs when we start from a vertex and follow the directed edges until we reach the same vertex again.
In this problem, we need to determine whether a given directed graph contains a cycle.
If a cycle exists, return
true.If no cycle exists, return
false.
We can solve this problem efficiently using Depth First Search (DFS) and a Recursion Stack.
2. Problem Understanding
We are given:
V: Number of vertices.adj[][]: Adjacency list representing the directed graph.
Our task is to check whether the graph contains at least one cycle.
Example 1
Input:
adj = [[1], [2], [0, 3], []];Graph representation:
0 → 1 → 2
↑ |
└───────┘
2 → 3Here, we have a cycle:
0 → 1 → 2 → 0
Output:
trueExplanation: Vertex 2 has an edge back to vertex 0. Since we can return to a previously visited vertex in the current DFS path, a cycle exists.
Example 2
Input:
adj = [[1, 2], [2], [3], []];Graph representation:
0
/ \
1 2
\ |
3Output:
falseExplanation: There is no directed path that returns to a vertex already present in its current DFS path. Therefore, no cycle exists.
3. Concept: What is Depth First Search (DFS)?
DFS is a graph traversal algorithm that explores one path as deeply as possible before moving to another path.
For example:
0 → 1 → 2 → 3DFS starts from vertex 0 and visits:
0 → 1 → 2 → 3After reaching the last vertex, it returns to the previous vertices using recursion.
DFS is useful for cycle detection because we can track which vertices are currently being explored.
4. Important Concept: Visited Array and Recursion Stack
To detect a cycle in a directed graph, we use two Boolean arrays.
A. visited[]
This array tells us whether a vertex has already been visited.
const visited = new Array(V).fill(false);For example:
visited[0] = true
visited[1] = true
visited[2] = falseThis means vertices 0 and 1 have already been visited, but vertex 2 has not.
B. pathVisited[]
This array tells us whether a vertex is currently present in the active DFS recursion path.
const pathVisited = new Array(V).fill(false);For example:
0 → 1 → 2During DFS:
pathVisited[0] = true
pathVisited[1] = true
pathVisited[2] = trueAll three vertices are currently in the DFS path.
If vertex 2 has an edge back to vertex 0, we find that:
visited[0] === true
pathVisited[0] === trueThis means we have reached a vertex that is already in the current DFS path.
Therefore, a cycle exists.
5. JavaScript Solution Using DFS
/**
* @param {number[][]} adj
* @returns {boolean}
*/
class Solution {
isCyclic(adj) {
const V = adj.length;
const visited = new Array(V).fill(false);
const pathVisited = new Array(V).fill(false);
const dfs = (node) => {
visited[node] = true;
pathVisited[node] = true;
for (let neighbor of adj[node]) {
// If neighbor is not visited
if (!visited[neighbor]) {
if (dfs(neighbor)) {
return true;
}
}
// If neighbor is already in current DFS path
else if (pathVisited[neighbor]) {
return true;
}
}
// Remove node from current DFS path
pathVisited[node] = false;
return false;
};
// Check all connected components
for (let i = 0; i < V; i++) {
if (!visited[i]) {
if (dfs(i)) {
return true;
}
}
}
return false;
}
}6. Step-by-Step Code Explanation
Step 1: Get the number of vertices
const V = adj.length;The length of the adjacency list gives us the total number of vertices.
For example:
adj = [[1], [2], [0, 3], []];Here, V = 4.
The vertices are:
0, 1, 2, 3
Step 2: Initialize the arrays
const visited = new Array(V).fill(false);
const pathVisited = new Array(V).fill(false);
Join the conversation! Your thoughts help the community grow.