Posts

Showing posts with the label Topological Sort

Topological Sort Code - Graphs

Image
  import java.util.*; // A Graph Node class GraphNode{     String name;     // list we use in adjacency list     ArrayList<GraphNode> neighbours;          // Constructor     GraphNode(String name){         this.name = name;         this.neighbours = new ArrayList<>();     } } public class Main {          ArrayList<GraphNode> nodesList;          // constructor     Main(){         this.nodesList = new ArrayList<>();     }          // function to add a directed edge from i->j     public void addDirectedAcyclicEdge(int source, int destination){         if(source==destination){             System.out.println("Can't add cyclic edge in graph, as for topological sort the graph...

Topological Sort Introduction - Graphs

Image
  "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...