⬅ Previous Topic
Flood Fill Algorithm - Graph BasedNext Topic ⮕
Detect Cycle in an Undirected Graph using BFS⬅ Previous Topic
Flood Fill Algorithm - Graph BasedNext Topic ⮕
Detect Cycle in an Undirected Graph using BFSTopic Contents
In an undirected graph, a cycle is formed when a path starts and ends at the same node, with at least one intermediate edge. The problem of detecting a cycle asks: Given an undirected graph, does it contain at least one cycle?
This is a fundamental graph problem often used in network reliability, dependency checking, and topology analysis.
visited
set to keep track of visited nodes.function hasCycle(graph) {
const visited = new Set();
function dfs(node, parent) {
visited.add(node);
for (const neighbor of graph[node] || []) {
if (!visited.has(neighbor)) {
if (dfs(neighbor, node)) return true;
} else if (neighbor !== parent) {
return true;
}
}
return false;
}
for (const node in graph) {
if (!visited.has(Number(node))) {
if (dfs(Number(node), -1)) return true;
}
}
return false;
}
const graph1 = {
0: [1],
1: [0, 2],
2: [1, 3],
3: [2, 0]
};
const graph2 = {
0: [1],
1: [0, 2],
2: [1]
};
console.log("Cycle in graph1:", hasCycle(graph1)); // true
console.log("Cycle in graph2:", hasCycle(graph2)); // false
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | Even if a cycle is found early, we must visit each node and edge in the worst connected component to be sure. |
Average Case | O(V + E) | DFS visits each node and edge once across all components, regardless of where the cycle is found. |
Worst Case | O(V + E) | Every node and edge in the graph must be visited to ensure there is no cycle. |
O(V)
Explanation: The space is used for the visited set and recursive call stack (or explicit stack), which grows up to the number of vertices.
⬅ Previous Topic
Flood Fill Algorithm - Graph BasedNext Topic ⮕
Detect Cycle in an Undirected Graph using BFSYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.