Cycle Detection in Directed Graphs

College Depth 188 in the knowledge graph I know this Set as goal
Unlocks 1 downstream topic
directed-graphs cycles algorithms

Core Idea

Cycle detection determines whether a directed graph contains any cycles. Algorithms like DFS-based backtracking identify cycles by marking vertices as visited, visiting, and done. Detecting cycles is essential for deadlock detection, dependency validation, and proving acyclicity.

Explainer

A cycle in a directed graph is a path that starts and ends at the same vertex, following edge directions the whole way. If your prerequisite on directed graphs introduced the idea that edges have a "one-way" quality, cycles are the case where a sequence of one-way steps somehow loops back to the origin — like a set of task dependencies where A requires B, B requires C, and C requires A. Such a cycle makes the dependency impossible to satisfy.

The standard algorithm for detecting cycles is a depth-first search (DFS) augmented with three vertex states, often called white, gray, and black (or unvisited, visiting, and done). When DFS begins exploring from a vertex, that vertex turns gray — it is "on the current path." When all its descendants have been fully explored, it turns black. The key insight: if DFS ever encounters a gray vertex through a forward edge, it has found a back edge, meaning the current path leads back to a vertex already on the current recursion stack. That is a cycle.

Why does the three-color distinction matter? A black vertex has already been fully processed — following an edge to it does not create a cycle, because that vertex's subtree contained no cycle and the black vertex itself has already been resolved. Only gray vertices signal a cycle, because gray means "ancestor in the current DFS path." Two colors (visited/unvisited) would confuse finished subtrees with active ancestors. The three-color scheme solves this precisely.

Real applications anchor this idea. Dependency resolution — package managers, build systems, task schedulers — must verify that their dependency graphs are acyclic before attempting to order tasks. Deadlock detection in operating systems reduces to finding cycles in a resource-allocation graph. Topological sort (which you'll study in directed acyclic graphs) is only valid when the graph has no cycles; cycle detection is the prerequisite check. Mastering this algorithm gives you both a practical tool and a concrete model for how directed graph structure constrains what computations are possible.

The DFS cycle-detection algorithm runs in O(V + E) time — linear in the size of the graph — because each vertex and edge is visited at most once. That efficiency makes it practical for real dependency graphs with thousands of nodes. As you move toward strongly connected components, you will see how cycle structure at a finer scale organizes the entire graph into a meaningful hierarchy.

Practice Questions 5 questions

Prerequisite Chain

Counting to 10Counting to 20Understanding ZeroThe Number ZeroCounting to FiveOne-to-One CorrespondenceCombining Small Groups Within 5Addition Within 10Addition Within 20Two-Digit Addition Without RegroupingTwo-Digit Addition with RegroupingAddition Within 100Repeated Addition as MultiplicationMultiplication Facts Within 100Division as Equal SharingDivision as Grouping (Measurement Division)Division: Grouping (Repeated Subtraction) ModelDivision: Fair Sharing ModelDivision as Equal SharingDivision as GroupingBasic Division FactsDivision Facts Within 100Two-Digit by One-Digit DivisionDivision with RemaindersRemainders and Quotients in DivisionDivision Word ProblemsIntroduction to Long DivisionFactors and MultiplesPrime and Composite NumbersEquivalent FractionsRelating Fractions and DecimalsDecimal Place ValueReading and Writing DecimalsComparing and Ordering DecimalsAdding and Subtracting DecimalsMultiplying DecimalsDividing DecimalsDividing FractionsMixed Number ArithmeticOrder of OperationsInteger Order of OperationsVariable ExpressionsCombining Like TermsOne-Step EquationsTwo-Step EquationsSolving Multi-Step EquationsEquations with Variables on Both SidesAngle Pairs: Complementary, Supplementary, and VerticalParallel Lines and TransversalsCorresponding AnglesAlternate Interior AnglesTriangle Angle Sum TheoremExterior Angle TheoremTriangle Inequality TheoremSimilar Triangles: AA SimilaritySimilar Triangles: SSS and SAS SimilarityProportions in Similar TrianglesRight Triangle Trigonometry IntroductionTrigonometric Ratios ReviewRadian MeasureConverting Between Degrees and RadiansThe Unit CircleGraphing Sine and CosineGraphing Tangent and Reciprocal Trigonometric FunctionsDerivatives of Trigonometric FunctionsAntiderivativesIterated Integrals and Fubini's TheoremDouble Integrals in Cartesian CoordinatesDouble Integrals over Rectangular RegionsDouble Integrals in Polar CoordinatesDouble Integrals: Definition and SetupIterated Integrals and Fubini's TheoremDouble Integrals over Rectangular RegionsDouble Integrals over General RegionsApplications of Double Integrals: Area, Mass, and MomentsTriple Integrals in Cartesian CoordinatesTriple Integrals in Cylindrical and Spherical CoordinatesChange of Variables and the Jacobian DeterminantApplications of Triple Integrals: Volume and MassVector Fields and Their RepresentationsLine Integrals of Vector FieldsGreen's TheoremSurface Integrals and Flux of Vector FieldsSurface Integrals and Flux of Vector FieldsDivergence Theorem: Flux and OutflowDivergence TheoremElectric FluxGauss's LawConductors in Electrostatic EquilibriumCapacitance and CapacitorsDielectricsDielectric Constant and Relative PermittivityElectric Field Inside Dielectric MaterialsDielectric Materials and PolarizationDielectric Susceptibility and PermittivityEnergy Density in Electric FieldsElectric Current and Current DensityElectrical Resistance and ResistivityOhm's Law and Circuit ElementsElectromotive Force (EMF) and BatteriesKirchhoff's Circuit Laws: Voltage and CurrentDC Circuit Network Analysis MethodsTransient Response in RC CircuitsRC CircuitsLC and RLC CircuitsAC Circuits: FundamentalsImpedance and ReactanceAC Power and ResonanceElectromagnetic WavesThe Electromagnetic SpectrumBlackbody Radiation and Planck's LawPhotoelectric EffectThe Photon: Light as QuantaCompton ScatteringWave-Particle Dualityde Broglie WavelengthHeisenberg Uncertainty PrincipleWavefunction and the Born RuleThe Schrödinger EquationState Vectors and WavefunctionsQuantum SuperpositionQuantum EntanglementBell Theorem and Bell InequalitiesPostulates of Quantum MechanicsScattering TheoryIntroduction to Scattering TheoryPartial Wave Analysis in ScatteringSpin Angular MomentumElectron Spin and Intrinsic Magnetic MomentStern-Gerlach Experiment: Spin Quantization and MeasurementElectron Diffraction and Matter Wave PropertiesDavisson-Germer Experiment: Crystal Diffraction of ElectronsElectron Diffraction and Matter Wave InterferenceWavefunctions and Probability Density InterpretationQuantum Superposition and Linear Combinations of StatesQuantum Operators and ObservablesCanonical Commutation Relations and UncertaintyHeisenberg Uncertainty Principle and Measurement LimitsTime-Independent Schrödinger Equation and EigenvaluesHydrogen Atom in Quantum MechanicsSpectral Lines and Energy TransitionsSelection Rules for Atomic TransitionsLS and jj Coupling Schemes in Multi-Electron AtomsPauli Exclusion Principle and Antisymmetric WavefunctionsElectron Configuration and the Aufbau PrincipleThe Periodic Table and Atomic Electronic StructureThe Periodic TableElectron ConfigurationPeriodic TrendsIonization EnergyIonic BondingLewis StructuresResonance Structures and Delocalized ElectronsResonance and Formal ChargeMolecular Polarity and Dipole MomentsIntermolecular ForcesStates of Matter and Phase Changes: Melting, Boiling, and SublimationGas Laws and the Ideal Gas EquationGas Stoichiometry and Volume-Volume CalculationsThermochemistry and EnthalpyHeat Capacity and CalorimetryEntropy and Molecular DisorderSpontaneity and ΔGEntropy and Gibbs Free EnergyChemical EquilibriumAcid-Base ChemistryOrganic Reaction Mechanisms and Arrow PushingElectrophilic Addition to AlkenesAromaticity and BenzeneDNA StructureCentral Dogma of Molecular BiologyThe Genetic CodeDNA MutationsDNA Repair MechanismsCell Cycle Checkpoints and Cancer PreventionMitotic Spindle Checkpoint and Chromosome SegregationKinetochore Structure and FunctionMitochondria: Structure and FunctionCellular Respiration OverviewBacterial Metabolism OverviewAntibiotic Resistance MechanismsInfectious Disease EpidemiologyFoundations of EpidemiologyMeasuring Disease Frequency: Incidence and PrevalenceEpidemiologic Study DesignsConfounding: Definition, Identification, and Causal CriteriaDirected Acyclic Graphs for Causal ModelingTopological Sorting and OrderingCycle Detection in Directed Graphs

Longest path: 189 steps · 934 total prerequisite topics

Prerequisites (2)

Leads To (1)