<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged topological-sort</title>
<link>https://coderlegion.com/tag/topological-sort</link>
<description>Powered by Question2Answer</description>
<item>
<title>Topological sort</title>
<link>https://coderlegion.com/1485/topological-sort</link>
<description>&lt;h3 id=&quot;what-is-topological-sort-&quot;&gt;What is topological sort ?&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;We need to schedule a series of tasks, such as classes or construction jobs, where we cannot start one task until after its  prerequisites are completed.&lt;/li&gt;
&lt;li&gt;We want to organize such tasks into a linear order that allows us to complete it one at a time, without violating any prerequisites.&lt;/li&gt;
&lt;li&gt;This problem can be modeled with DAG, directed acyclic graph&lt;/li&gt;
&lt;li&gt;Graph is directed since one task is dependent on another, so that means the relation between tasks is directed.&lt;/li&gt;
&lt;li&gt;Acyclic - We cannot have cycles in the graph, since that would mean conflicting series of prerequisite tasks that could not be completed without violating any prerequisites.&lt;/li&gt;
&lt;li&gt;The process of laying out the vertices of a DAG  in a linear order  to meet the prerequisite rule is called topological sort.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;how-to-do-it-&quot;&gt;How to do it ?&lt;/h3&gt;
&lt;p&gt;2 ways to implement a topological sort &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;BFS approach (Kahn's algorithm)&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DFS approach&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;BFS approach:&lt;/strong&gt;  &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In BFS approach we visit every node and find in-degree for each node (in-degree -&amp;gt; no of edges/ how many nodes are connected to that node)&lt;/li&gt;
&lt;li&gt;Finding in-degree in case of DAG is simply loop through all the nodes and increase the in-degree count for each adjacent node by 1.&lt;/li&gt;
&lt;li&gt;We keep the nodes with in-degree 0 into a queue, and start processing the queue.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;DFS approach:&lt;/strong&gt; &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In DFS approach we visit each node and its adjacent nodes, we only push the node to a stack once all the dependencies are visited first, so we naturally we are visiting all the dependencies first and then the node itself, so we end up ordered items naturally.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;working-code&quot;&gt;Working code&lt;/h3&gt;
&lt;h4 id=&quot;bfs-approach&quot;&gt;BFS approach&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;const graph = {
  7: [11, 8],
  5: [11],
  3: [10, 8],
  11: [2, 9, 10],
  8: [9],
  2: [],
  9: [],
  10: [],
};

function toposortBFS(graph) {
  const order = [];
  const indgree = {};

  /*Set indegrees for all node to 0*/
  for (let node of Object.keys(graph)) {
    indgree[node] = 0;
  }

  /*Increment in-degrees of all adjacent nodes of all nodes in graph -&amp;gt; get in-degree for all the nodes in a graph*/
  for (let node of Object.keys(graph)) {
    for (let adjNode of graph[node]) {
      /*IMP: (?? 0) is necessary in case of connected components in  the graph*/
      indgree[adjNode] = (indgree[adjNode] ?? 0) + 1;
    }
  }

  const queue = [];
  /*Push all nodes with 0 in-degree to a queue*/
  for (let node of Object.keys(indgree)) {
    if (indgree[node] === 0) {
      queue.push(node);
    }
  }

  /*Process queue such that we keep pushing adj node with 0 in-degree,  decrement indegrees of adj node, dequeued elements are in sorted order*/
  while (queue.length &amp;gt; 0) {
    const currentNode = queue.shift();
    order.push(currentNode);

    for (let adjNode of graph[currentNode]) {
      indgree[adjNode] -= 1;
      if (indgree[adjNode] === 0) {
        queue.push(adjNode);
      }
    }
  }

  /*We need to check if all the items are processed from the graph - if not, we have a cycle in the graph - this could be used to detect cycles as well*/
  return order.length === Object.keys(graph).length ? order : [];
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;dfs-approach&quot;&gt;DFS approach&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;const graph = {
    7:[11,8],
    5:[11],
    3:[10,8],
    11:[2,9,10],
    8:[9],
    2:[],
    9:[],
    10:[]
};

function toposortDFS (graph) {
    const order = [];
    const visited = {};
    
    for (let node of Object.keys(graph)) {
        visited[node] = 0;
    }
    
    function dfs(node) {
        if(visited[node]){ return; }
        visited[node] = 1;
        for(let adjNode of graph[node]) {
            dfs(adjNode);
        }
        order.push(node);
    }
    
    for(let node of Object.keys(graph)) {
        if(!visited[node]) {
            dfs(node);
        }
    }

    return order.reverse();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;applications&quot;&gt;Applications&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Representing course pre-requisites&lt;/li&gt;
&lt;li&gt;Detecting dead locks&lt;/li&gt;
&lt;li&gt;Pipeline of computing jobs&lt;/li&gt;
&lt;li&gt;Checking for symbolic link loops&lt;/li&gt;
&lt;li&gt;Evaluating formulae in spreadsheets&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Java</category>
<guid isPermaLink="true">https://coderlegion.com/1485/topological-sort</guid>
<pubDate>Sat, 15 Mar 2025 05:05:07 +0000</pubDate>
</item>
</channel>
</rss>