diff --git a/C++/README.md b/C++/README.md index 53d3d45..cad171d 100644 --- a/C++/README.md +++ b/C++/README.md @@ -7,6 +7,7 @@ # Graph Algorithms * Topological Sort _(Depth-First Search)_ +* Topological Sort _(Kahn's Algorithm)_ ## Mathematics ### Linear Algebra diff --git a/C++/graph_algorithms/topological_sort.cpp b/C++/graph_algorithms/topological_sort.cpp index acd0d3c..48bb41e 100644 --- a/C++/graph_algorithms/topological_sort.cpp +++ b/C++/graph_algorithms/topological_sort.cpp @@ -46,12 +46,47 @@ void dfs(int vertex, const vector>& adjacency_list, deque dfs_topological_sort(const vector>& adjacency_list) { - vector colors(adjacency_list.size()); + int n = adjacency_list.size(); + vector colors(n); deque 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 +kahns_algorithm_topological_sort(const vector>& adjacency_list) +{ + int n = adjacency_list.size(); + deque order; + vector indegrees(n); + for (int i = 0; i < n; i++) { + for (const auto& neighbour : adjacency_list[i]) { + indegrees[neighbour]++; + } + } + deque 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 diff --git a/C++/graph_algorithms/topological_sort.h b/C++/graph_algorithms/topological_sort.h index b9998d8..7fd77c5 100644 --- a/C++/graph_algorithms/topological_sort.h +++ b/C++/graph_algorithms/topological_sort.h @@ -23,6 +23,9 @@ namespace mehara::graph { std::deque dfs_topological_sort(const std::vector>& adjacency_list); -} +std::deque kahns_algorithm_topological_sort( + const std::vector>& adjacency_list); + +} // namespace mehara::graph #endif // MEHARA_TOPOLOGICAL_SORT_H_