{"id":11248,"date":"2025-11-27T10:38:42","date_gmt":"2025-11-27T05:08:42","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=11248"},"modified":"2026-01-11T19:15:26","modified_gmt":"2026-01-11T13:45:26","slug":"kahns-algorithm-topological-sort-bfs","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/kahns-algorithm-topological-sort-bfs\/","title":{"rendered":"Kahn Algorithm Topological Sort BFS"},"content":{"rendered":"\n<!-- PrismJS for Syntax Highlighting -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\" rel=\"stylesheet\">\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n  <button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n  <h1 class=\"wp_blog_main-heading\"><\/h1>\n\n  <div class=\"wp_blog_explanation\">\n    <h2>Kahn&#8217;s Algorithm (BFS) (Topological Sort) [DAG]<\/h2>\n    <p><strong>\n        It is a linear ordering of nodes of a DAG(Directed Acyclic Graph) such that for every directed edge (u -> v), node u comes before v.\n    <\/strong><\/p>\n\n    <h2>Example<\/h2>\n    <p><strong>An adjacency list represents a graph.<\/strong><\/p>\n        <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/11\/Screenshot-2025-11-26-at-11.51.35-AM.png\" alt=\"\">\n    <pre><strong>\n        const adj = [\n            [],          \/\/ 0\n            [],          \/\/ 1\n            [3],         \/\/ 2 -> 3\n            [1],         \/\/ 3 -> 1\n            [0, 1],      \/\/ 4 -> 0, 1\n            [0, 2]       \/\/ 5 -> 0, 2 \n        ]<\/strong>\n    <\/pre>\n\n    <h2>Representation<\/h2>\n    <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/11\/Screenshot-2025-11-26-at-11.51.35-AM.png\" alt=\"\">\n    <p><strong><code>5, 0, 2, 3, 1, 4<\/code><\/strong><\/p>\n\n    <h2>Indegree<\/h2>\n    <ul>\n      <li>Node 0 \u2192 indegree 2<\/li>\n      <li>Node 1 \u2192 indegree 2<\/li>\n      <li>Node 2 \u2192 indegree 1<\/li>\n      <li>Node 3 \u2192 indegree 1<\/li>\n      <li>Node 4 \u2192 indegree 0<\/li>\n      <li>Node 5 \u2192 indegree 0<\/li>\n    <\/ul>\n\n    <h2>Code<\/h2>\n  <div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n    <pre>\n        function topologicalSortBFS(n, graph) {\n          let indegree = new Array(n).fill(0);\n\n          for(let i=0; i < n; i++){\n            for(let node of graph[i]) {\n              indegree[node]++;\n            }\n          }\n          console.log(indegree);\n          let q = [];\n          let ans = [];\n          \/\/ Push indegree = 0 elements in queue\n          for(let i = 0; i < n; i++){\n            if(indegree[i] == 0){\n              q.push(i);\n            }\n          }\n\n          \/\/ while(q.length) take out curr element from queue and explore neighbors, reduce indegree\n          \n          while(q.length) {\n            let curr = q.shift();\n            ans.push(curr);\n            for(let neighbor of graph[curr]){\n              indegree[neighbor]--;\n              if(indegree[neighbor] == 0){\n                q.push(neighbor);\n              }\n            }\n          }\n\n          if(ans.length != n) {\n            console.log(\"Graph has a cycle, and topo sort is not possible.\");\n            return [];\n          }\n          return ans;\n        }\n\n        const n = 6;\n        const adj = [\n            [],          \/\/ 0\n            [],          \/\/ 1\n            [3],         \/\/ 2 -> 3\n            [1],         \/\/ 3 -> 1\n            [0, 1],      \/\/ 4 -> 0, 1\n            [0, 2]       \/\/ 5 -> 0, 2 \n        ];\n        console.log(topologicalSortBFS(n, adj));\n    <\/pre>\n    <\/div>\n\n     <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre>\nfrom collections import deque\n\ndef topological_sort_bfs(n, graph):\n    indegree = [0] * n\n\n    # Calculate indegree\n    for i in range(n):\n        for node in graph[i]:\n            indegree[node] += 1\n\n    print(indegree)\n\n    q = deque()\n    ans = []\n\n    # Push nodes with indegree 0\n    for i in range(n):\n        if indegree[i] == 0:\n            q.append(i)\n\n    while q:\n        curr = q.popleft()\n        ans.append(curr)\n\n        for neighbor in graph[curr]:\n            indegree[neighbor] -= 1\n            if indegree[neighbor] == 0:\n                q.append(neighbor)\n\n    if len(ans) != n:\n        print(\"Graph has a cycle, and topo sort is not possible.\")\n        return []\n\n    return ans\n\n\nn = 6\nadj = [\n    [],\n    [],\n    [3],\n    [1],\n    [0, 1],\n    [0, 2]\n]\n\nprint(topological_sort_bfs(n, adj))\n    <\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre>\nimport java.util.*;\n\nclass Solution {\n    static List<Integer> topologicalSortBFS(int n, List<List<Integer>> graph) {\n        int[] indegree = new int[n];\n\n        \/\/ Calculate indegree\n        for (int i = 0; i < n; i++) {\n            for (int node : graph.get(i)) {\n                indegree[node]++;\n            }\n        }\n\n        System.out.println(Arrays.toString(indegree));\n\n        Queue<Integer> q = new LinkedList<>();\n        List<Integer> ans = new ArrayList<>();\n\n        \/\/ Add nodes with indegree 0\n        for (int i = 0; i < n; i++) {\n            if (indegree[i] == 0) {\n                q.add(i);\n            }\n        }\n\n        while (!q.isEmpty()) {\n            int curr = q.poll();\n            ans.add(curr);\n\n            for (int neighbor : graph.get(curr)) {\n                indegree[neighbor]--;\n                if (indegree[neighbor] == 0) {\n                    q.add(neighbor);\n                }\n            }\n        }\n\n        if (ans.size() != n) {\n            System.out.println(\"Graph has a cycle, and topo sort is not possible.\");\n            return new ArrayList<>();\n        }\n\n        return ans;\n    }\n\n    public static void main(String[] args) {\n        int n = 6;\n        List<List<Integer>> graph = new ArrayList<>();\n\n        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());\n\n        graph.get(2).add(3);\n        graph.get(3).add(1);\n        graph.get(4).add(0);\n        graph.get(4).add(1);\n        graph.get(5).add(0);\n        graph.get(5).add(2);\n\n        System.out.println(topologicalSortBFS(n, graph));\n    }\n}\n  <\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre>\n#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nvector<int> topologicalSortBFS(int n, vector<vector<int>>& graph) {\n    vector<int> indegree(n, 0);\n\n    for (int i = 0; i < n; i++) {\n        for (int node : graph[i]) {\n            indegree[node]++;\n        }\n    }\n\n    for (int x : indegree) cout << x << \" \";\n    cout << endl;\n\n    queue<int> q;\n    vector<int> ans;\n\n    for (int i = 0; i < n; i++) {\n        if (indegree[i] == 0) {\n            q.push(i);\n        }\n    }\n\n    while (!q.empty()) {\n        int curr = q.front();\n        q.pop();\n        ans.push_back(curr);\n\n        for (int neighbor : graph[curr]) {\n            indegree[neighbor]--;\n            if (indegree[neighbor] == 0) {\n                q.push(neighbor);\n            }\n        }\n    }\n\n    if (ans.size() != n) {\n        cout << \"Graph has a cycle, and topo sort is not possible.\" << endl;\n        return {};\n    }\n\n    return ans;\n}\n\nint main() {\n    int n = 6;\n    vector<vector<int>> graph(n);\n\n    graph[2].push_back(3);\n    graph[3].push_back(1);\n    graph[4].push_back(0);\n    graph[4].push_back(1);\n    graph[5].push_back(0);\n    graph[5].push_back(2);\n\n    vector<int> res = topologicalSortBFS(n, graph);\n    for (int x : res) cout << x << \" \";\n}\n<\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre>\n#include &lt;stdio.h&gt;\n\nint graph[6][2] = {\n    {},\n    {},\n    {3},\n    {1},\n    {0, 1},\n    {0, 2}\n};\n\nint size[] = {0, 0, 1, 1, 2, 2};\n\nint main() {\n    int n = 6;\n    int indegree[6] = {0};\n\n    \/\/ Calculate indegree\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < size[i]; j++) {\n            indegree[graph[i][j]]++;\n        }\n    }\n\n    for (int i = 0; i < n; i++)\n        printf(\"%d \", indegree[i]);\n    printf(\"\\n\");\n\n    int queue[6], front = 0, rear = 0;\n    int ans[6], idx = 0;\n\n    for (int i = 0; i < n; i++) {\n        if (indegree[i] == 0) {\n            queue[rear++] = i;\n        }\n    }\n\n    while (front < rear) {\n        int curr = queue[front++];\n        ans[idx++] = curr;\n\n        for (int j = 0; j < size[curr]; j++) {\n            int neighbor = graph[curr][j];\n            indegree[neighbor]--;\n            if (indegree[neighbor] == 0) {\n                queue[rear++] = neighbor;\n            }\n        }\n    }\n\n    if (idx != n) {\n        printf(\"Graph has a cycle, and topo sort is not possible.\\n\");\n        return 0;\n    }\n\n    for (int i = 0; i < n; i++)\n        printf(\"%d \", ans[i]);\n\n    return 0;\n}\n<\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n    <pre>\nusing System;\nusing System.Collections.Generic;\n\nclass Solution {\n    static List<int> TopologicalSortBFS(int n, List<int>[] graph) {\n        int[] indegree = new int[n];\n\n        for (int i = 0; i < n; i++) {\n            foreach (int node in graph[i]) {\n                indegree[node]++;\n            }\n        }\n\n        Console.WriteLine(string.Join(\" \", indegree));\n\n        Queue<int> q = new Queue<int>();\n        List<int> ans = new List<int>();\n\n        for (int i = 0; i < n; i++) {\n            if (indegree[i] == 0) {\n                q.Enqueue(i);\n            }\n        }\n\n        while (q.Count > 0) {\n            int curr = q.Dequeue();\n            ans.Add(curr);\n\n            foreach (int neighbor in graph[curr]) {\n                indegree[neighbor]--;\n                if (indegree[neighbor] == 0) {\n                    q.Enqueue(neighbor);\n                }\n            }\n        }\n\n        if (ans.Count != n) {\n            Console.WriteLine(\"Graph has a cycle, and topo sort is not possible.\");\n            return new List<int>();\n        }\n\n        return ans;\n    }\n\n    static void Main() {\n        int n = 6;\n        List<int>[] graph = new List<int>[n];\n\n        for (int i = 0; i < n; i++)\n            graph[i] = new List<int>();\n\n        graph[2].Add(3);\n        graph[3].Add(1);\n        graph[4].Add(0);\n        graph[4].Add(1);\n        graph[5].Add(0);\n        graph[5].Add(2);\n\n        var result = TopologicalSortBFS(n, graph);\n        Console.WriteLine(string.Join(\" \", result));\n    }\n}\n<\/pre>\n    <\/div>\n\n<\/div>  \n\n<\/div>\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Kahn&#8217;s Algorithm (BFS) (Topological Sort) [DAG] It is a linear ordering of nodes of a DAG(Directed Acyclic Graph) such that for every directed edge (u -> v), node u comes before v. Example An adjacency list represents a graph. const adj = [ [], \/\/ 0 [], \/\/ 1 [3], \/\/ 2 -> 3<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,322,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":["post-11248","post","type-post","status-publish","format-standard","category-algorithms","category-algorithms-and-data-structures","category-c-c-plus-plus","category-csharp","category-cplusplus","category-data-structures","category-data-structures-and-algorithms","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11248","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=11248"}],"version-history":[{"count":4,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11248\/revisions"}],"predecessor-version":[{"id":11437,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11248\/revisions\/11437"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=11248"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=11248"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=11248"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}