Topological Sort Introduction - Graphs



 
"What is topological Sort?"
  • A topological sort sorts the given actions in such a way that if there is a dependency of one action on another action, then the dependent action always comes after its parent action.
  • In graph terms, the topological sort is a linear ordering of its nodes such that for every directed edge from node x to node y,  x -> y (y is dependent on x), x always comes before y in that ordering.
  • We can do topological sort only for Directed Acyclic Graphs
  • We use DFS like algorithm to do the topological sorting of the graph. The only difference between DFS and topological sorting is that we can do DFS for any type of graph but the topological sorting can only be done for Directed Acyclic Graph (DAG).
  • We can get multiple answers or linear ordering of vertices of the graph in Topological sort. It all depends upon from where we start doing the topological sort.

Algorithm for Topological Sort : [Time Coplexity - O(V+E)  Space Complexity- O(V+E)]

We are going to use a stack here

1. For all unvisited nodes in the graph do :
            2. If the current node has unvisited adjacent node (directed), then go to that adjacent node. Do this for all unvisited adjacent nodes recursively.
            3. If the current node has no unvisited adjacent nodes or has no adjacent nodes, add it to stack, mark it as visited, and proceed to the next iteration.
4. Pop everything from stack and display

Comments

Popular posts from this blog

Binary Heap - Introduction

Divide and Conquer - Introduction

Bubble Sort