Detect a Cycle in an Undirected Graph
Given vertexCount vertices numbered 0 through vertexCount - 1 and undirected adjacency lists adjacency, return true if any component contains a cycle,…
Given vertexCount vertices numbered 0 through vertexCount - 1 and undirected adjacency lists adjacency, return true if any component contains a cycle, otherwise false. Every edge occurrence appears once in each endpoint’s row, with matching reverse multiplicity. Self-edges are excluded. Parallel edges are distinct: two edges between the same vertices form a cycle without reusing an edge. Neighbor row order is preserved.
- 1 <= vertexCount <= 10000 - 1 <= undirected edge count <= 10000 - adjacency has exactly vertexCount rows; isolated vertices may have empty rows - Every neighbor is an integer ID from 0 to vertexCount - 1 - Reverse edge occurrences have matching multiplicity; no self-edges - The visualizer supports at most 24 vertices and 48 undirected edge occurrences; Run Code and Submit support the full coding domain.
Example 1: input vertexCount = 6, adjacency = [[1,3],[0,2,4],[1,5],[0,4],[1,3,5],[2,4]]; output true. The path 1–2–5–4–1 closes a cycle with distinct edges.
Example 2: input vertexCount = 4, adjacency = [[1,2],[0],[0,3],[2]]; output false. Every connection belongs to the tree; revisiting a parent through the reverse edge does not form a cycle.
Category: Graphs. Topic: graph. Difficulty: Medium. Patterns: graph-traversal, bfs, dfs.