⬅ Previous Topic
Detect Cycle in an Undirected Graph using DFSNext Topic ⮕
Distance of Nearest Cell Having 1 - Grid BFS⬅ Previous Topic
Detect Cycle in an Undirected Graph using DFSNext Topic ⮕
Distance of Nearest Cell Having 1 - Grid BFSTopic Contents
The problem is to detect whether a cycle exists in an undirected graph using the Breadth-First Search (BFS) traversal technique.
A cycle in an undirected graph occurs when there is a path that starts and ends at the same node without reusing any edge.
This problem is important in applications like deadlock detection, circuit analysis, and validating graph structures.
visited
set.[current, parent]
pairs.[node, parent]
.node
:[neighbor, node]
to queue.function hasCycle(graph) {
const visited = new Set();
const bfs = (start) => {
const queue = [[start, -1]];
visited.add(start);
while (queue.length > 0) {
const [node, parent] = queue.shift();
for (const neighbor of graph[node] || []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push([neighbor, node]);
} else if (neighbor !== parent) {
return true; // Cycle detected
}
}
}
return false;
};
for (const node in graph) {
if (!visited.has(Number(node))) {
if (bfs(Number(node))) {
return true;
}
}
}
return false;
}
const graph1 = { 0: [1, 2], 1: [0, 2], 2: [0, 1] };
console.log("Cycle detected:", hasCycle(graph1)); // true
const graph2 = { 0: [1], 1: [0, 2], 2: [1], 3: [] };
console.log("Cycle detected:", hasCycle(graph2)); // false
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | In the best case (no cycle and early exit), every vertex and edge in the connected components must still be traversed to ensure the absence of a cycle. |
Average Case | O(V + E) | Each node and edge is visited once. The BFS explores all nodes and edges reachable from each unvisited node, ensuring complete coverage. |
Worst Case | O(V + E) | In the worst case, such as a complete graph, the algorithm still performs BFS for all nodes and edges before finding or ruling out a cycle. |
O(V)
Explanation: The queue and visited set both store up to O(V) elements, where V is the number of vertices in the graph.
⬅ Previous Topic
Detect Cycle in an Undirected Graph using DFSNext Topic ⮕
Distance of Nearest Cell Having 1 - Grid 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.