Detect a Cycle in a Directed Graph
Given vertexCount vertices numbered 0 through vertexCount - 1 and directed adjacency lists adjacency, return true if any component contains a directed cycle,…
Given vertexCount vertices numbered 0 through vertexCount - 1 and directed adjacency lists adjacency, return true if any component contains a directed cycle, otherwise false. Each entry adjacency[u] contains the outgoing neighbors of u. Self-loops and repeated directed edges are valid; a visited vertex outside the current DFS path does not by itself prove a cycle.
- 1 <= vertexCount <= 10000 - 1 <= directed edge occurrences <= 10000 - adjacency has exactly vertexCount rows; isolated vertices may have empty rows - Every neighbor is an integer ID from 0 to vertexCount - 1 - The visualizer supports at most 24 vertices and 48 directed edge occurrences; Run Code and Submit support the full coding domain.
Example 1: input vertexCount = 6, adjacency = [[1],[2,5],[3],[4],[1],[]]; output true. The directed path 1 → 2 → 3 → 4 → 1 returns to vertex 1.
Example 2: input vertexCount = 4, adjacency = [[1,2],[2],[],[0,2]]; output false. Several paths converge on vertex 2, but none returns to an ancestor.
Category: Graphs. Topic: graph. Difficulty: Hard. Patterns: graph-traversal, dfs, bfs.