Data Structures and Algorithms B
  • Introduction
  • Stable Marrage
  • Huffman Codes
    • ABL
    • Implementation
  • Graph Algorithms
    • Connect Component
    • Bipartiteness
    • Strongly Connected Components
      • Implementation
    • Topological Sort
      • Implementation 1
      • Implementation 2
    • Dijkstra’s Shortest Path
    • Minimum Spanning Tree
      • Prims
        • Implementation 1
      • Kruskels
        • Implementation 1
      • Traveling Salesman Problem
    • k-Clustering
    • Dynamic Programming with Trees
      • Implementation 1
      • Implementation 2
    • Disjoint Sets
      • Implementation
    • Eularian Cycle
      • Implementation
    • Hamiltonian Path
      • Implementation
  • Divide and Conquer
    • Merge Sort
    • Integer Multiplication
    • Closest Pair
    • Master Method
  • Dynamic Programming
    • Interval Scheduling
    • Knapsack Problem
  • Network Flow
    • Maximum Network Flow
    • Improvements
    • Image Segmentation
  • String Algorithms
    • Z Algorithm
    • Boyer-Moore
    • Knuth-Morris-Pratt
    • Suffix Trees
      • Naive Implementation
      • Ukkonens Algorithm
        • Implementation
      • Applications
        • Longest Common Substring
        • Longest Palindromic Substring
        • Longest Repeated Substring
  • Randomized Algorithms
    • Bloom Filters
      • Implementation
Powered by GitBook
On this page

Was this helpful?

  1. Graph Algorithms
  2. Topological Sort

Implementation 1

Implementation

void erase(Node &n, Graph &g)
{
    if (g.graph.find(n) == g.graph.end()) { 
        cout << "Node does not exist" << endl; return; 
    }
    g.graph.erase(n);

    for (auto &i : g.graph) {
        if (i.second.find(n) != i.second.end()) {
            i.second.erase(n);
        }
    }
}

vector<string> top_ordering(Graph g)
{
    vector<string> t_order;
    t_order.reserve(g.graph.size());
    bool stop = false;
    while (!stop) {
        stop = true;
        for (auto i : g.graph) {
            if (i.second.empty()) {
                stop = false;
                t_order.push_back(i.first.id);
                erase(const_cast<Node&>(i.first), g);
                break;
            }
        }
    }

    if (!g.graph.empty()) {
        cout << "No topological ordering exists" << endl;
        return vector<string>();
    }
    else return t_order;
}

A Few Remarks/Thoughts

  • I initially passed not my reference because I didn't want to mess with graph internally.

  • Can be used to validate if a graph as a cycle, although this will be slow. Time complexity for this is:(O(∣V∣)+O(∣V∣))2(O(|V|) + O(|V|))^2(O(∣V∣)+O(∣V∣))2

PreviousTopological SortNextImplementation 2

Last updated 5 years ago

Was this helpful?