Java icon indicating copy to clipboard operation
Java copied to clipboard

feat: Add Topological Sorting using DFS

Open Raghu0703 opened this issue 2 weeks ago • 0 comments

Description

This PR implements Topological Sorting using Depth-First Search (DFS) for Directed Acyclic Graphs (DAGs) as requested in issue #6938.

Changes Made

  • ✅ Implemented TopologicalSortDFS.java with DFS-based topological sorting algorithm
  • ✅ Added cycle detection using recursion stack to validate DAG property
  • ✅ Created comprehensive test suite (TopologicalSortDFSTest.java) with 20+ test cases
  • ✅ Added practical examples (TopologicalSortExample.java) demonstrating real-world usage
  • ✅ Included complete Javadoc documentation for all methods

Algorithm Details

  • Approach: DFS traversal with visited array and recursion stack for cycle detection
  • Time Complexity: O(V + E) where V = number of vertices, E = number of edges
  • Space Complexity: O(V) for recursion stack and auxiliary data structures
  • Key Features:
    • Detects cycles and throws IllegalArgumentException for non-DAG graphs
    • Handles disconnected components correctly
    • Includes isDAG() utility method for graph validation

Implementation Highlights

  1. Cycle Detection: Uses recursion stack to accurately detect back edges
  2. Adjacency List: Efficient graph representation using List<List<Integer>>
  3. Stack-based Ordering: Pushes vertices to stack after DFS completion for correct topological order
  4. Edge Case Handling: Properly handles empty graphs, single vertices, and null inputs

Test Coverage

The test suite includes comprehensive coverage for:

  • ✅ Simple and complex DAGs with multiple dependencies
  • ✅ Linear graphs and disconnected components
  • ✅ Cycle detection (self-loops, simple cycles, complex cycles)
  • ✅ Edge cases (empty graph, single vertex, null input)
  • ✅ Real-world scenarios:
    • Task scheduling with dependencies
    • Course prerequisite ordering
    • Build system dependency resolution

Example Usage

Raghu0703 avatar Nov 25 '25 06:11 Raghu0703