| 188 | } |
| 189 | |
| 190 | std::vector<El::Int> |
| 191 | depth_first_search(El::Int root, |
| 192 | const std::map<El::Int, std::set<El::Int>>& edges) |
| 193 | { |
| 194 | |
| 195 | // Initialize data structures |
| 196 | std::unordered_map<El::Int, bool> is_visited, is_sorted; |
| 197 | std::vector<El::Int> sorted_nodes; |
| 198 | std::stack<El::Int> search_stack; |
| 199 | search_stack.push(root); |
| 200 | |
| 201 | // Visit nodes until search stack is exhausted |
| 202 | while (!search_stack.empty()) { |
| 203 | const auto& node = search_stack.top(); |
| 204 | search_stack.pop(); |
| 205 | if (!is_sorted[node]) { |
| 206 | if (is_visited[node]) { |
| 207 | // Add node to sorted list if we have already visited |
| 208 | is_sorted[node] = true; |
| 209 | sorted_nodes.push_back(node); |
| 210 | } |
| 211 | else { |
| 212 | // Visit node and add neighbors to search stack |
| 213 | is_visited[node] = true; |
| 214 | search_stack.push(node); |
| 215 | for (const auto& neighbor : get_neighbors(node, edges)) { |
| 216 | if (!is_visited[neighbor] && !is_sorted[neighbor]) { |
| 217 | search_stack.push(neighbor); |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // Return list of sorted nodes |
| 225 | return sorted_nodes; |
| 226 | } |
| 227 | |
| 228 | std::vector<El::Int> |
| 229 | topological_sort(const std::set<El::Int>& nodes, |
no test coverage detected