Skip to content

Commit 1c22abb

Browse files
Merge pull request #252 from Abhi8756/feature/TopologicalSort-cpp
feat: Implement Topological Sort algorithm for DAGs in C++
2 parents 7d63ebc + e0a2ab2 commit 1c22abb

2 files changed

Lines changed: 653 additions & 0 deletions

File tree

Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
# Graph Algorithms in C++
2+
3+
This directory contains efficient implementations of fundamental graph algorithms in C++, showcasing various graph traversal, topological ordering, and analysis techniques.
4+
5+
## 📁 Available Implementations
6+
7+
### 1. Topological Sort - `topological_sort.cpp`
8+
**Description**: Linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge (u, v), vertex u comes before v in the ordering.
9+
10+
**Key Features**:
11+
- **Two Algorithms**: DFS-based and Kahn's algorithm (BFS-based)
12+
- **Cycle Detection**: Validates DAG property before sorting
13+
- **Multiple Orderings**: Find all possible topological orderings
14+
- **Labeled Vertices**: Support for custom vertex names/labels
15+
- **Interactive Mode**: Create custom graphs and analyze them
16+
- **Real-world Examples**: Course prerequisites, task scheduling
17+
18+
**Time Complexity**: O(V + E) where V is vertices and E is edges
19+
**Space Complexity**: O(V) for auxiliary data structures
20+
21+
**Applications**:
22+
- Task scheduling with dependencies
23+
- Course prerequisite planning
24+
- Build systems and compilation order
25+
- Deadlock detection in operating systems
26+
- Symbol table construction in compilers
27+
- Package dependency resolution
28+
29+
**Algorithm Implementations**:
30+
31+
1. **DFS-based Topological Sort**:
32+
- Uses depth-first search with post-order traversal
33+
- Maintains a stack to store vertices in reverse topological order
34+
- Natural recursive implementation
35+
36+
2. **Kahn's Algorithm (BFS-based)**:
37+
- Uses in-degree counting and queue-based processing
38+
- Processes vertices with zero in-degree first
39+
- Iterative approach with better cycle detection
40+
41+
**Code Highlights**:
42+
```cpp
43+
// Create a directed graph
44+
DirectedGraph graph(6);
45+
graph.setVertexLabel(0, "Math101");
46+
graph.setVertexLabel(1, "CS101");
47+
48+
// Add prerequisite relationships
49+
graph.addEdge(0, 2); // Math101 -> Math201
50+
graph.addEdge(1, 3); // CS101 -> CS201
51+
52+
// Check if graph is a DAG
53+
if (!graph.hasCycle()) {
54+
// DFS-based topological sort
55+
vector<int> dfsResult = topologicalSortDFS(graph);
56+
57+
// Kahn's algorithm
58+
vector<int> kahnResult = topologicalSortKahn(graph);
59+
60+
// Find all possible orderings
61+
vector<vector<int>> allOrderings = allTopologicalSorts(graph);
62+
}
63+
```
64+
65+
**Features Demonstrated**:
66+
- **DirectedGraph Class**: Complete graph representation with adjacency lists
67+
- **Cycle Detection**: DFS-based cycle detection using color coding
68+
- **Vertex Labeling**: Custom labels for better readability
69+
- **Multiple Examples**: Course scheduling, task dependencies, linear chains
70+
- **Error Handling**: Comprehensive validation and error messages
71+
72+
## 🚀 How to Run
73+
74+
### Compile and Run Topological Sort
75+
```bash
76+
# Compile
77+
g++ -o topological_sort topological_sort.cpp
78+
79+
# Run
80+
./topological_sort
81+
```
82+
83+
### Program Modes
84+
1. **Demonstration Mode**: See predefined examples with detailed explanations
85+
2. **Interactive Mode**: Create your own directed graph and analyze it
86+
87+
## 📊 Algorithm Comparison
88+
89+
| Algorithm | Approach | Implementation | Cycle Detection | Best Use Case |
90+
|-----------|----------|----------------|-----------------|---------------|
91+
| DFS-based | Recursive | Stack-based | During traversal | Simple graphs |
92+
| Kahn's | Iterative | Queue-based | Explicit check | Large graphs |
93+
94+
## 🎯 When to Use Topological Sort
95+
96+
**✅ Use Topological Sort When**:
97+
- You have a directed acyclic graph (DAG)
98+
- Need to order tasks with dependencies
99+
- Scheduling problems with prerequisites
100+
- Building dependency resolution systems
101+
- Detecting deadlocks in systems
102+
103+
**❌ Cannot Use When**:
104+
- Graph contains cycles (not a DAG)
105+
- Working with undirected graphs
106+
- Need shortest paths (use Dijkstra/Bellman-Ford)
107+
- Finding connected components (use DFS/BFS)
108+
109+
## 🔧 Graph Input Formats
110+
111+
The implementation supports flexible graph creation:
112+
113+
**Method 1: Programmatic Creation**
114+
```cpp
115+
DirectedGraph graph(5);
116+
graph.addEdge(0, 1);
117+
graph.addEdge(0, 2);
118+
graph.addEdge(1, 3);
119+
```
120+
121+
**Method 2: Interactive Input**
122+
```
123+
Enter number of vertices: 4
124+
Enter directed edges:
125+
0 1
126+
0 2
127+
1 3
128+
2 3
129+
-1 -1
130+
```
131+
132+
**Method 3: Labeled Vertices**
133+
```cpp
134+
graph.setVertexLabel(0, "Database");
135+
graph.setVertexLabel(1, "Programming");
136+
graph.setVertexLabel(2, "DataStructures");
137+
```
138+
139+
## 📚 Educational Value
140+
141+
This implementation demonstrates:
142+
143+
**Graph Theory Concepts**:
144+
- Directed Acyclic Graphs (DAGs)
145+
- Graph traversal algorithms
146+
- Cycle detection techniques
147+
- Topological ordering properties
148+
149+
**Algorithm Design Patterns**:
150+
- Depth-First Search (DFS)
151+
- Breadth-First Search (BFS)
152+
- Backtracking for all solutions
153+
- State-space search
154+
155+
**Data Structures**:
156+
- Adjacency list representation
157+
- Stack and queue usage
158+
- Vector and map containers
159+
- Color coding for graph states
160+
161+
**Real-world Applications**:
162+
- Dependency resolution
163+
- Task scheduling
164+
- Compilation systems
165+
- Package managers
166+
167+
## 🔍 Complexity Analysis
168+
169+
### Time Complexity
170+
- **DFS-based**: O(V + E) - visits each vertex and edge once
171+
- **Kahn's Algorithm**: O(V + E) - processes each vertex and edge once
172+
- **All Orderings**: O(V! × V) - exponential for finding all solutions
173+
- **Cycle Detection**: O(V + E) - single DFS traversal
174+
175+
### Space Complexity
176+
- **Graph Storage**: O(V + E) for adjacency list
177+
- **Auxiliary Space**: O(V) for visited arrays, stacks, queues
178+
- **Result Storage**: O(V) for single ordering, O(V! × V) for all orderings
179+
180+
## 🤝 Contributing
181+
182+
Feel free to contribute additional graph algorithms:
183+
184+
**Graph Traversal**:
185+
- Breadth-First Search (BFS)
186+
- Depth-First Search (DFS)
187+
- Bidirectional Search
188+
189+
**Shortest Path Algorithms**:
190+
- Dijkstra's Algorithm
191+
- Bellman-Ford Algorithm
192+
- Floyd-Warshall Algorithm
193+
- A* Search Algorithm
194+
195+
**Minimum Spanning Tree**:
196+
- Kruskal's Algorithm
197+
- Prim's Algorithm
198+
- Borůvka's Algorithm
199+
200+
**Advanced Graph Algorithms**:
201+
- Strongly Connected Components (Tarjan's, Kosaraju's)
202+
- Articulation Points and Bridges
203+
- Maximum Flow algorithms
204+
- Graph Coloring algorithms
205+
206+
## 📖 References
207+
208+
- [Introduction to Algorithms - CLRS](https://mitpress.mit.edu/books/introduction-algorithms)
209+
- [Graph Theory - Diestel](https://www.springer.com/gp/book/9783662575604)
210+
- [Algorithms in C++ - Sedgewick](https://www.informit.com/store/algorithms-in-c-plus-plus-parts-1-4-fundamentals-data-9780201350883)
211+
- [GeeksforGeeks Topological Sort](https://www.geeksforgeeks.org/topological-sorting/)
212+
213+
---
214+
215+
**Author**: Abhijit
216+
**Hacktoberfest 2025**: ✅
217+
**Language**: C++
218+
**Category**: Graph Algorithms

0 commit comments

Comments
 (0)