Skip to content

Commit

Permalink
[C++] Graph Algorithms: Topological Sort (Kahn's Algorithm)
Browse files Browse the repository at this point in the history
  • Loading branch information
amanmehara committed Mar 23, 2024
1 parent 0dcb5f5 commit d49dd9c
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
1 change: 1 addition & 0 deletions C++/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

# Graph Algorithms
* Topological Sort _(Depth-First Search)_
* Topological Sort _(Kahn's Algorithm)_

## Mathematics
### Linear Algebra
Expand Down
39 changes: 37 additions & 2 deletions C++/graph_algorithms/topological_sort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,47 @@ void dfs(int vertex, const vector<vector<int>>& adjacency_list,

deque<int> dfs_topological_sort(const vector<vector<int>>& adjacency_list)
{
vector<int> colors(adjacency_list.size());
int n = adjacency_list.size();
vector<int> colors(n);
deque<int> order;
for (int i = 0; i < adjacency_list.size(); i++) {
for (int i = 0; i < n; i++) {
dfs(i, adjacency_list, colors, order);
}
return order;
}

deque<int>
kahns_algorithm_topological_sort(const vector<vector<int>>& adjacency_list)
{
int n = adjacency_list.size();
deque<int> order;
vector<int> indegrees(n);
for (int i = 0; i < n; i++) {
for (const auto& neighbour : adjacency_list[i]) {
indegrees[neighbour]++;
}
}
deque<int> q;
for (int i = 0; i < n; i++) {
if (indegrees[i] == 0) {
q.push_back(i);
}
}
while (!q.empty()) {
int vertex = q.front();
q.pop_front();
order.push_back(vertex);
for (const auto& neighbour : adjacency_list[vertex]) {
indegrees[neighbour]--;
if (indegrees[neighbour] == 0) {
q.push_back(neighbour);
}
}
}
if (order.size() != n) {
throw logic_error("Graph has at least one cycle.");
}
return order;
}

} // namespace mehara::graph
5 changes: 4 additions & 1 deletion C++/graph_algorithms/topological_sort.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ namespace mehara::graph {
std::deque<int>
dfs_topological_sort(const std::vector<std::vector<int>>& adjacency_list);

}
std::deque<int> kahns_algorithm_topological_sort(
const std::vector<std::vector<int>>& adjacency_list);

} // namespace mehara::graph

#endif // MEHARA_TOPOLOGICAL_SORT_H_

0 comments on commit d49dd9c

Please sign in to comment.