<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Graph Garden on Medium]]></title>
        <description><![CDATA[Stories by Graph Garden on Medium]]></description>
        <link>https://medium.com/@mathchannel338?source=rss-fdc2523529c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kVDIXKuFrBIuUVbgGpHH2Q.png</url>
            <title>Stories by Graph Garden on Medium</title>
            <link>https://medium.com/@mathchannel338?source=rss-fdc2523529c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:39:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mathchannel338/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dijkstra’s Algorithm — Shortest Paths with Non-Negative Weights]]></title>
            <link>https://medium.com/@mathchannel338/dijkstras-algorithm-shortest-paths-with-non-negative-weights-d6ac99e21e77?source=rss-fdc2523529c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ac99e21e77</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Graph Garden]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 04:47:35 GMT</pubDate>
            <atom:updated>2026-07-22T04:47:35.491Z</atom:updated>
            <content:encoded><![CDATA[<p><em>BFS, but with weighted edges. The graph algorithm behind every car-navigation app and most internet routers — and its correctness proof fits in a few lines.</em></p><p>This is the third article in a <a href="https://medium.com/@mathchannel338/four-graph-algorithms-visualized-a-guided-tour-5b3b90c16d54">series on graph algorithms</a>. The earlier articles cover <a href="https://medium.com/p/ad1743b24be1">graph traversal</a> and the <a href="https://medium.com/@mathchannel338/kruskals-algorithm-building-the-cheapest-tree-c6cc211cbce6">minimum spanning tree problem with Kruskal’s</a>. This article is readable on its own — you only need to know that a <em>weighted graph</em> assigns a number (“weight” or “cost”) to each edge, and that a <em>path</em> in such a graph has a total weight equal to the sum of its edge weights.</p><p><strong>Dijkstra’s algorithm</strong> answers a simple question: given a weighted graph and a starting vertex 𝑠, what is the cheapest path from 𝑠 to every other vertex?</p><p>The setup is so common that you have used Dijkstra’s many times without knowing it. Every car-navigation app runs a variant on a road-network graph. Every router on the public internet running OSPF runs Dijkstra’s on its local topology. Every game-AI pathfinder traces back to it. If a vertex represents a place or a state and edges have positive costs, this is your algorithm.</p><blockquote><em>🎥 </em><strong><em>Watch the video</em></strong><em> on </em><a href="https://youtu.be/0L0-_DGcyrY"><em>Graph Garden</em></a><em>.</em></blockquote><h3>The problem</h3><p>You have a weighted, directed graph 𝐺 = (𝑉, 𝐸) and a designated <strong>source</strong> vertex 𝑠. Every edge (𝑣, 𝑤) carries a weight 𝑐(𝑣, 𝑤), interpreted as the cost or distance of traversing that edge.</p><p>You want, for every vertex 𝑣, the <strong>shortest-path distance</strong> 𝑑(𝑣) — the minimum total weight of any 𝑠-to-𝑣 path. Usually you also want the path itself, not just its length.</p><p>The catch: <strong>every edge weight must be non-negative</strong>, 𝑐(𝑣, 𝑤) ≥ 0. We’ll see exactly where this assumption is used, and exactly what breaks if it fails.</p><h3>Watching Dijkstra’s</h3><p>Before the algorithm itself, here is the rough idea on a concrete example. The basic idea is this:</p><blockquote>Grow outward from 𝑠, always finalizing the closest remaining vertex, and use it to improve the distance estimates of its neighbors.</blockquote><p>Let us see what that means in practice. Throughout the run, every vertex 𝑣 carries a <strong>tentative distance</strong> 𝑑(𝑣) — the length of the shortest path from 𝑠 to 𝑣 <em>known so far</em>. At the start, 𝑑(𝑠) = 0 and 𝑑(𝑣) = ∞ for every other vertex. The algorithm then repeatedly picks the vertex with the smallest tentative distance, <strong>settles</strong> it — declares its distance final — and uses its outgoing edges to try to lower its neighbors’ tentative distances.</p><p>Here is Dijkstra’s running on a 6-vertex graph from source 𝐴 to target 𝐹. Each panel below shows one settle operation: which vertex was just settled, what its 𝑑 became, and how its neighbors’ tentative distances updated. Purple arrows are <strong>parent pointers</strong>: whenever 𝑑(𝑤) improves via an edge out of 𝑣, we record 𝑣 as the parent 𝑝(𝑤), so that the shortest path itself can be traced back afterwards. The gold path in the last panel is the final 𝐴-to-𝐹 shortest path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UoHGAAEeMAd2_UBIU2lSlQ.png" /><figcaption>Dijkstra’s step by step, one settle per panel</figcaption></figure><p><strong>Step 1</strong> — initialize and settle 𝐴. We set 𝑑(𝐴) = 0 and 𝑑(𝑣) = ∞ for every other vertex. 𝐴 has the smallest 𝑑, so we settle it first. Its outgoing edges go to 𝐵 (weight 4) and 𝐶 (weight 2), so we set 𝑑(𝐵) = 4 and 𝑑(𝐶) = 2, with both parents pointing to 𝐴. The smallest unsettled 𝑑 is now 𝐶.</p><p><strong>Step 2</strong> — settle 𝐶. From 𝐶 we can reach 𝐵 with total cost 2 + 1 = 3, which beats the previous 𝑑(𝐵) = 4. We update 𝑑(𝐵) = 3 and 𝑝(𝐵) = 𝐶, so 𝐵’s parent pointer now goes to 𝐶 instead of to 𝐴. We also set 𝑑(𝐷) = 10 (via 𝐶, edge weight 8) and 𝑑(𝐸) = 9 (via 𝐶, edge weight 7). Smallest unsettled: 𝐵.</p><p><strong>Step 3</strong> — settle 𝐵. Via 𝐵 we reach 𝐷 with cost 3 + 5 = 8, which beats the previous 𝑑(𝐷) = 10. Update 𝑑(𝐷) = 8, 𝑝(𝐷) = 𝐵. 𝐵 has no edge to 𝐸, so 𝑑(𝐸) is unchanged.</p><p><strong>Step 4</strong> — settle 𝐷. Via 𝐷, we can reach 𝐸 with cost 8 + 2 = 10, but 𝑑(𝐸) is already 9 — no improvement. We do reach 𝐹 for the first time: 𝑑(𝐹) = 8 + 6 = 14. Smallest unsettled: 𝐸.</p><p><strong>Step 5</strong> — settle 𝐸 (the next smallest 𝑑 = 9). Going through 𝐸 reaches 𝐹 with cost 9 + 3 = 12, beating the earlier 𝑑(𝐹) = 14. Update 𝑑(𝐹) = 12, 𝑝(𝐹) = 𝐸. Smallest unsettled: 𝐹.</p><p><strong>Step 6</strong> — settle 𝐹. No outgoing edges to relax. Done.</p><p>The shortest path 𝐴 → 𝐶 → 𝐸 → 𝐹 has total weight 2 + 7 + 3 = 12. It’s traced in the figure by following parent pointers back from 𝐹: 𝑝(𝐹) = 𝐸, 𝑝(𝐸) = 𝐶, 𝑝(𝐶) = 𝐴.</p><p>A note on the other vertices. 𝐵 and 𝐷 settle along the way at 𝑑(𝐵) = 3 and 𝑑(𝐷) = 8 — these are still their correct shortest distances from 𝐴 — but they don’t lie on the 𝐴-to-𝐹 path. Dijkstra’s outputs shortest distances to <em>every</em> vertex, not just to one target; the gold path in the final panel is the one we recovered by walking parent pointers back from 𝐹.</p><p>A small but important thing to notice: <strong>𝐵’s parent changes during the walk</strong>. After Step 1, 𝑝(𝐵) = 𝐴 (we reached 𝐵 directly from 𝐴 with cost 4). After Step 2, 𝑝(𝐵) = 𝐶 (because 𝐴 → 𝐶 → 𝐵 with cost 3 turned out to be cheaper). Parent pointers are not final until their vertex is settled — but once a vertex is settled, its parent is locked in.</p><h3>The idea</h3><p>With the walk seen on a concrete example, the general pattern is easy to state. BFS visits vertices in order of their distance from 𝑠, counting distance as number of edges (see the <a href="https://medium.com/@mathchannel338/dfs-and-bfs-how-to-visit-everything-in-a-graph-ad1743b24be1">DFS and BFS article</a> for details). <strong>Dijkstra’s algorithm is exactly BFS generalized to edge weights.</strong> We still visit vertices in order of their distance from 𝑠 — but distance is now total edge weight, not edge count. A plain queue isn’t enough, because the next vertex to settle might not be the one we discovered first; it’s the one whose tentative distance is currently smallest. So the frontier becomes a <strong>priority queue</strong>, and we always pop its minimum.</p><p>The loop we watched above, written out: maintain a tentative distance 𝑑(𝑣) for every vertex. Initialize 𝑑(𝑠) = 0 and 𝑑(𝑣) = ∞ for everyone else. Then repeat:</p><ol><li>Among unsettled vertices, pick the one with the smallest 𝑑.</li><li><strong>Settle</strong> it — declare its distance final.</li><li>Use its outgoing edges to try to improve its neighbors’ tentative distances.</li></ol><pre>𝑑(𝑠) ← 0,  𝑑(𝑣) ← ∞ for every other 𝑣<br>while there is an unsettled vertex:<br>    𝑣 ← unsettled vertex with smallest 𝑑(𝑣)<br>    settle 𝑣<br>    for each neighbor 𝑤 of 𝑣:<br>        if 𝑑(𝑣) + 𝑐(𝑣, 𝑤) &lt; 𝑑(𝑤):<br>            𝑑(𝑤) ← 𝑑(𝑣) + 𝑐(𝑣, 𝑤)<br>            𝑝(𝑤) ← 𝑣</pre><p>Two notes on the pseudocode. First, 𝑐(𝑣, 𝑤) is just shorthand for “weight of edge (𝑣, 𝑤).” Second, the last two lines maintain exactly the parent pointers we saw in the example: whenever a shorter path to 𝑤 through 𝑣 is found, 𝑤’s parent is updated to 𝑣. Once the algorithm finishes, walking parent pointers back from any vertex to 𝑠 gives the shortest path itself.</p><p>The third bullet (“try to improve neighbors”) is sometimes called <em>relaxing</em> the outgoing edges. We won’t lean on the word in this article — the operation is just “update 𝑑(𝑤) if a shorter path through 𝑣 has been found.”</p><h3>Why this works</h3><p>So why can we say that the distances Dijkstra’s outputs are correct? Let us reason about its correctness. The claim to prove is:</p><blockquote><strong><em>When Dijkstra’s settles a vertex 𝑣, the current 𝑑(𝑣) is the true shortest distance from 𝑠 to 𝑣.</em></strong></blockquote><p>If this holds for every 𝑣, then by the time the algorithm finishes, every distance is correct.</p><p>Here is the proof. Suppose for contradiction that we are about to settle 𝑣 at 𝑑(𝑣), but there is some path 𝑃 from 𝑠 to 𝑣 whose total weight is strictly less than 𝑑(𝑣). Consider the moment 𝑃 first crosses from a settled vertex to an unsettled one. Such a moment exists, because 𝑃 starts at 𝑠 (which is settled the moment we begin) and ends at 𝑣 (which is still unsettled — we’re about to settle it now). Call that crossing edge (𝑥, 𝑦), where 𝑥 is settled and 𝑦 is not.</p><p>Then:</p><blockquote><em>𝑑(𝑦) ≤ 𝑑(𝑥) + 𝑐(𝑥, 𝑦) ≤ (total length of 𝑃) &lt; 𝑑(𝑣).</em></blockquote><p>Why each step?</p><ul><li>𝑑(𝑦) ≤ 𝑑(𝑥) + 𝑐(𝑥, 𝑦) because when 𝑥 was settled, we processed its outgoing edges, including (𝑥, 𝑦), and updated 𝑑(𝑦) to be at most this value.</li><li>𝑑(𝑥) + 𝑐(𝑥, 𝑦) ≤ (total length of 𝑃) because 𝑑(𝑥) is the correct shortest distance to 𝑥 (by induction — 𝑥 was settled earlier), and the remaining portion of 𝑃 from 𝑦 to 𝑣 has length ≥ 0. <strong>This step uses non-negativity.</strong></li></ul><p>So 𝑑(𝑦) &lt; 𝑑(𝑣). But Dijkstra’s was about to settle 𝑣 because it had the smallest 𝑑 among unsettled vertices — including 𝑦, which is unsettled. Contradiction.</p><p>The whole argument turns on one inequality: <em>the remaining portion of 𝑃 from 𝑦 to 𝑣 has length ≥ 0</em>. Drop the assumption that edge weights are non-negative and that step fails. The algorithm’s correctness vanishes.</p><h3>When non-negativity breaks</h3><p>Here is a different six-vertex graph (new edge weights, including one negative one — the 𝐶 → 𝐸 edge of weight −5, drawn in orange). Try to find the shortest path from 𝐴 to 𝐹 by eye before reading on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taztkjhxfY8NTiAhelw1iw.png" /><figcaption>One negative edge (orange) breaks Dijkstra’s</figcaption></figure><p>Walk through Dijkstra’s:</p><p><strong>Step 0.</strong> 𝑑(𝐴) = 0, every other 𝑑 is ∞. Smallest unsettled: 𝐴.</p><p><strong>Step 1 — settle 𝐴.</strong> Update 𝑑(𝐵) = 1 (via 𝐴 → 𝐵) and 𝑑(𝐶) = 4 (via 𝐴 → 𝐶). Smallest unsettled: 𝐵.</p><p><strong>Step 2 — settle 𝐵.</strong> Update 𝑑(𝐷) = 1 + 3 = 4 and 𝑑(𝐸) = 1 + 2 = 3. Smallest unsettled: 𝐸 (at 𝑑 = 3, which beats 𝐶 at 𝑑 = 4 and 𝐷 at 𝑑 = 4).</p><p><strong>Step 3 — settle 𝐸. This is where it goes wrong.</strong> Dijkstra’s locks in 𝑑(𝐸) = 3 and processes 𝐸’s outgoing edges, giving 𝑑(𝐹) = 3 + 5 = 8. But notice: 𝐸 is being settled <em>before</em> 𝐶 — and the only way to take advantage of 𝐶 → 𝐸’s negative weight would be to update 𝑑(𝐸) <em>after</em> 𝐶 is settled. That chance is now lost.</p><p><strong>Step 4 — settle 𝐶.</strong> Now 𝐶’s outgoing edges are processed. 𝐶 → 𝐵 with weight 1 would give 𝑑(𝐵) = 4 + 1 = 5, but 𝑑(𝐵) is already 1 — no improvement. The edge 𝐶 → 𝐸 with weight −5 <em>would</em> give 𝑑(𝐸) = 4 + (−5) = −1 — a real improvement. But 𝐸 is already settled, and Dijkstra’s never reconsiders. The chance is gone.</p><p><strong>Step 5 — settle 𝐷.</strong> Update 𝑑(𝐹) = min(8, 4 + 2) = 6.</p><p><strong>Step 6 — settle 𝐹.</strong> Dijkstra’s done. It outputs 𝑑(𝐹) = 6, with the path 𝐴 → 𝐵 → 𝐷 → 𝐹.</p><p>Now look at the eighth panel. The true shortest path is <strong>𝐴 → 𝐶 → 𝐸 → 𝐹</strong>, with total weight 4 + (−5) + 5 = <strong>4</strong>. Dijkstra’s was off by 2. And the true 𝑑(𝐸) is not 3 but <strong>−1</strong> — the value Dijkstra’s would have computed if only it had settled 𝐶 before 𝐸.</p><p>The proof in the previous section told us this would happen. When we argued 𝑑(𝑥) + 𝑐(𝑥, 𝑦) ≤ (length of 𝑃), we relied on the remainder of 𝑃 being non-negative. With one negative edge, a path that looks more expensive at first can secretly be cheaper. Dijkstra’s whole strategy — settle in order of current 𝑑, never reconsider — depends on that property never failing.</p><p>The fix is the next algorithm in this series, <strong>Bellman-Ford</strong>, which gives up Dijkstra’s clever ordering and brute-forces every edge enough times to converge even with negative edges.</p><h3>Complexity</h3><p>The dominant cost is operating on the priority queue. There are 𝑛 settle operations (one per vertex) and at most 𝑚 update operations (one per edge examined). With a <strong>binary heap</strong>, both extract-min and decrease-key are 𝑂(log 𝑛), giving:</p><blockquote><em>Dijkstra’s with a binary heap: </em><strong><em>𝑂((𝑛 + 𝑚) log 𝑛)</em></strong><em>.</em></blockquote><p>A <strong>Fibonacci heap</strong> improves this to 𝑂(𝑚 + 𝑛 log 𝑛), but the constant factors are bad in practice and the simpler binary heap is what most code actually uses. Other variants exist for special cases — dense graphs do well with a plain 𝑂(𝑛²) array, and graphs with small integer weights have specialized linear-time methods — but the binary-heap bound is the one to remember.</p><h3>Where this matters</h3><p>Dijkstra’s is everywhere. Three of the most visible applications:</p><h3>Road navigation</h3><p>Every car-navigation app — Google Maps, Apple Maps, Waze, every GPS unit — runs Dijkstra’s (or a heuristic-augmented version called <strong>A*</strong>) on a road network. Vertices are intersections; edges are road segments with weights equal to estimated travel time. Real systems do extensive preprocessing — <em>contraction hierarchies</em> are the standard, allowing continental-scale queries in milliseconds — but the core algorithm is Dijkstra’s. Travel times are non-negative, so the assumption holds.</p><p><strong>A*</strong> is worth a paragraph because it shows up so often. It is Dijkstra’s with a small modification: when picking the next vertex to settle, instead of “smallest 𝑑(𝑣),” pick “smallest 𝑑(𝑣) + ℎ(𝑣),” where ℎ(𝑣) is a heuristic estimate of the distance from 𝑣 to the goal (for road networks, straight-line distance works). If ℎ never overestimates the true remaining distance — <em>admissible heuristic</em> — then A* still returns optimal paths, but it explores far fewer vertices because it has a sense of which direction to head. Pathfinding in games uses A* by default for the same reason.</p><h3>Link-state network routing</h3><p>Internet routing protocols come in two families. <em>Distance-vector</em> protocols (RIP) are distributed versions of Bellman-Ford. <em>Link-state</em> protocols (<strong>OSPF</strong>, IS-IS) work differently: every router learns the full topology of its network area, then runs Dijkstra’s locally to compute the shortest path to every other router. Routers exchange link-state updates so everyone agrees on the topology, and each then computes its own forwarding table independently.</p><p>The reason link-state protocols use Dijkstra’s instead of Bellman-Ford is that they have the full topology to work with. When you know the whole graph, the fast non-negative algorithm is the obvious choice.</p><h3>Game AI and pathfinding</h3><p>When a character in a video game walks across a map, the engine usually runs A* (or some variant of Dijkstra’s) over a grid or navigation mesh. Edge weights encode movement cost — walking on rough terrain might cost more than smooth ground, climbing more than walking. As long as costs are non-negative, Dijkstra’s is the right tool. Most game engines bake heavy optimization into their A* implementations (hierarchical pathfinding, jump-point search, path caching), but the algorithm at the core is the one in the box above.</p><h3>Other appearances</h3><p>A short tour of other contexts where Dijkstra’s shows up: <strong>VLSI routing</strong> (laying out connections on a chip), <strong>flight planning</strong> (cheapest sequence of legs), <strong>DNA sequence alignment</strong> (modelled as shortest paths in an edit graph), <strong>resource allocation</strong> in scheduling problems, <strong>electrical network analysis</strong> for current flow problems. Anywhere “cheapest path” makes sense and costs are non-negative.</p><h3>What to take away</h3><p>Three things to take away:</p><ul><li><strong>Dijkstra’s is BFS plus weights.</strong> BFS uses a queue and visits in edge-count order; Dijkstra’s uses a priority queue and visits in weight order. Same skeleton, smarter frontier.</li><li><strong>Settle-once is fast but fragile.</strong> The algorithm’s speed comes from never reconsidering a settled vertex. Non-negativity is the property that makes this safe. Drop it and the algorithm breaks in obvious, demonstrable ways.</li><li><strong>Parent pointers give paths, not just distances.</strong> Always store them. The cost is one extra field per vertex; the benefit is that you can recover the actual path, not just its length.</li></ul><h3>Where to go next</h3><p>The natural follow-up handles exactly the case Dijkstra’s cannot:</p><ul><li><strong>Bellman-Ford — Shortest Paths When Weights Can Be Negative</strong> — slower, but works whenever negative cycles are absent. As a bonus, it can detect negative cycles when they exist, with one extra pass.</li></ul><p>These articles are being published one at a time. The <a href="https://medium.com/@mathchannel338/four-graph-algorithms-visualized-a-guided-tour-5b3b90c16d54">hub article</a> keeps the full series map up to date — bookmark it if you want to be sure to catch the rest. If you like learning visually, the <a href="https://www.youtube.com/@graphgarden">Graph Garden YouTube channel</a> has a video for each one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ac99e21e77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kruskal’s Algorithm — Building the Cheapest Tree]]></title>
            <link>https://medium.com/@mathchannel338/kruskals-algorithm-building-the-cheapest-tree-c6cc211cbce6?source=rss-fdc2523529c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6cc211cbce6</guid>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Graph Garden]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 02:58:54 GMT</pubDate>
            <atom:updated>2026-06-17T02:58:54.837Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The first weighted graph algorithm to learn. Four lines of pseudocode, a correctness proof, and a broad set of applications.</em></p><p>So far in this <a href="https://medium.com/p/5b3b90c16d54">series on graph algorithms</a>, we have only asked an unweighted question: <em>can you visit every vertex, and in what order?</em> Now we add the next layer. Edges carry <strong>weights</strong> — a cost, a distance, a capacity — and the questions get harder. The first one to tackle is the <strong>minimum spanning tree (MST)</strong> problem, and the simplest and most intuitive solution is <strong>Kruskal’s algorithm</strong>.</p><p>If you have not yet read the <a href="https://medium.com/p/ad1743b24be1">previous article on DFS and BFS</a>, this one is still readable on its own, but you may find the assumed background (graphs as 𝐺 = (𝑉, 𝐸), 𝑛 = |𝑉|, 𝑚 = |𝐸|) less natural. The series <a href="https://medium.com/p/5b3b90c16d54">hub</a> keeps the full map.🎥 <em>A companion video for this article is available on </em><a href="https://youtu.be/zpOI2epGKok"><em>Graph Garden</em></a><em>.</em></p><h3>The problem</h3><p>You have a <strong>connected, undirected, weighted</strong> graph 𝐺. Every edge (𝑢, 𝑣) carries a positive weight 𝑐(𝑢, 𝑣). You want to find a subset 𝑇 ⊆ 𝐸 of edges that:</p><ol><li><strong>connects every vertex</strong> (so the graph (𝑉, 𝑇) is still connected — 𝑇 <em>spans</em> the graph),</li><li><strong>contains no cycles</strong> (so (𝑉, 𝑇) is a <em>tree</em>),</li><li>has the <strong>smallest possible total weight</strong> among all such subsets.</li></ol><p>Such a 𝑇 is a <strong>minimum spanning tree</strong> (MST for short) of 𝐺. (There may be more than one if some edges share weights — the MST is not always unique. The <em>minimum total weight</em> is, though.)</p><p>A natural worry: does an MST always exist? Yes — because the graph is connected, at least one spanning tree exists (start from any vertex and keep adding tree edges to reach unvisited vertices, just like a DFS or BFS would). There are finitely many spanning trees, so the one of minimum total weight exists.</p><h3>A worked example</h3><p>Before the algorithm itself, here is the rough idea on a concrete example. The basic idea is this:</p><blockquote>Keep adding the lowest-weight edge that does not create a cycle.</blockquote><p>Let us see what that means in practice. Here is a 7-vertex graph with 9 weighted edges. Kruskal’s processes edges in increasing weight order. Each panel below shows one stage of the algorithm; vertex <strong>ring colors indicate connected components</strong> in the current 𝑇. Discarded edges (those that would have closed a cycle) appear as dashed red lines so you can see what Kruskal’s <em>rejected</em> alongside what it <em>accepted</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9O4_5E3GZ_pI5y7uLMexw.png" /><figcaption>Kruskal — Pick the lowest-weight edge unless it close a cycle</figcaption></figure><p><strong>Step 0:</strong> every vertex is alone — seven components, seven different rings.</p><p><strong>Steps 1–3:</strong> edges 𝐴–𝐵 (weight 1) and 𝐵–𝐶 (weight 2) join into a single component {𝐴, 𝐵, 𝐶}. Then comes 𝐴–𝐶 (weight 3) — but 𝐴 and 𝐶 are now in the same component, so this edge would close the 𝐴-𝐵-𝐶 triangle into a cycle. Kruskal’s <strong>discards it</strong>. This is the key point of the algorithm: it doesn’t blindly take the lowest-weight edges; it takes the lowest-weight edges that <em>connect new things</em>.</p><p><strong>Steps 4–6:</strong> the same pattern plays out on the right. 𝐷–𝐸 (4) and 𝐸–𝐹 (5) join {𝐷, 𝐸, 𝐹}; then 𝐷–𝐹 (6) is discarded because it would close the 𝐷-𝐸-𝐹 triangle. Notice the two big components ({𝐴, 𝐵, 𝐶} and {𝐷, 𝐸, 𝐹}) have different ring colors — they are still separate sub-trees in 𝑇.</p><p><strong>Step 7:</strong> edge 𝐵–𝐷 (weight 7) connects the two components. After this step, every vertex except 𝐺 is in one big component (look at the ring colors merging in the figure).</p><p><strong>Step 8:</strong> edge 𝐶–𝐸 (weight 8) is examined next — but 𝐶 and 𝐸 are both already in the big component, so this edge is <strong>discarded</strong> too. Even though 𝐶 and 𝐸 weren’t directly connected by anything we took before, the chain 𝐶–𝐵–𝐷–𝐸 already provides a path. Adding 𝐶–𝐸 would create a longer cycle.</p><p><strong>Step 9:</strong> finally, edge 𝐹–𝐺 (weight 9) brings 𝐺 into the component, and the MST is complete. It has 𝑛 − 1 = 6 edges: 𝐴–𝐵, 𝐵–𝐶, 𝐷–𝐸, 𝐸–𝐹, 𝐵–𝐷, 𝐹–𝐺, with total weight 1 + 2 + 4 + 5 + 7 + 9 = 28.</p><p>A few things to notice. <strong>Three edges were discarded</strong> mid-run (𝐴–𝐶, 𝐷–𝐹, 𝐶–𝐸) — this is not unusual. Most real graphs have many more edges than 𝑛 − 1, so most of what Kruskal’s looks at is rejected. <strong>The discards happened at three different stages</strong> of the algorithm: 𝐴–𝐶 inside a small component on the left, 𝐷–𝐹 inside a small component on the right, and 𝐶–𝐸 across the merged component after 𝐵–𝐷 had joined them. Whenever an edge’s two endpoints are already in the same connected piece of 𝑇, that edge has to go.</p><h3>A natural idea</h3><blockquote>Keep adding the lowest-weight edge that does not create a cycle.</blockquote><p>That single sentence captures the essence of the algorithm. Sort all edges by weight, smallest first. Process them in order. For each edge, ask: <em>does adding this edge to my current set create a cycle?</em> If yes, throw it away. If no, add it to the tree. Stop when every vertex is connected.</p><pre>sort edges by weight (smallest first)<br>𝑇 ← empty set<br>for each edge (𝑢, 𝑣) in sorted order:<br>    if 𝑢 and 𝑣 are NOT already connected in 𝑇:<br>        add (𝑢, 𝑣) to 𝑇<br>return 𝑇</pre><p>That’s it. Four lines. This is <strong>Kruskal’s algorithm</strong>, due to Joseph Kruskal in 1956.</p><p>Two things to note. First, the greedy strategy — always take the lowest-weight available edge — actually <em>works</em>. We treat why in detail in the Correctness section that follows. Second, the algorithm is structurally indifferent to the rest of the graph: it processes edges in sorted order and makes one local decision each time. No layered exploration, no priority queue updates, no backtracking.</p><h3>Correctness</h3><p>So why can we say that this algorithm finds an MST? Let us reason about its correctness.</p><p>The key to establishing correctness is the following theorem.</p><p><strong>Theorem.</strong> Let 𝑇 be a spanning tree of a connected, weighted graph 𝐺. Then the following (a) and (b) are equivalent.</p><p>(a) 𝑇 is a minimum-weight spanning tree.<br>(b) For every edge 𝑒 = 𝑥𝑦 ∈ 𝐸(𝐺) ∖ 𝐸(𝑇), no edge heavier than 𝑐(𝑒) lies on the path in 𝑇 connecting 𝑥 and 𝑦 (see the figure below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rP5-TzhhTzekL9X5qijqzw.png" /><figcaption>The non-tree edge 𝑒 = 𝑥𝑦 (dashed) and the path in 𝑇 joining 𝑥 and 𝑦 (highlighted)</figcaption></figure><p>Taking this theorem as given, let us show the correctness of Kruskal’s algorithm. It suffices to verify that the spanning tree produced by Kruskal’s algorithm satisfies (b).</p><p>Let 𝑇 be the spanning tree obtained by running Kruskal’s algorithm, and let 𝑒 be any edge not contained in 𝑇. Adding 𝑒 to 𝑇 creates a cycle; removing 𝑒 from that cycle leaves a path in 𝑇 connecting the two endpoints of 𝑒. At the moment the algorithm decides whether to add 𝑒, every edge on this path has already been selected. Since edges are processed in increasing order of weight, every edge on this path has weight less than (or equal to) that of 𝑒. As 𝑒 was arbitrary, 𝑇 satisfies property (b). ∎</p><h3>The hidden subproblem: Union-Find</h3><p>The pseudocode says “check if 𝑢 and 𝑣 are already connected.” How does Kruskal’s do that fast?</p><p>The trick is to maintain the current partition of the vertices into connected components explicitly. Adding edge (𝑢, 𝑣) creates a cycle if and only if 𝑢 and 𝑣 are already in the same component. So we need two operations on this partition:</p><ul><li>find(𝑣) — return an identifier for 𝑣&#39;s current component.</li><li>union(𝑢, 𝑣) — merge the components of 𝑢 and 𝑣 into one.</li></ul><p>The data structure that supports both <em>almost</em> in constant time is called the <strong>Union-Find</strong> (or <em>disjoint set union</em>) structure. Internally, each component is represented as a rooted tree, where each vertex stores a pointer to its parent and the root is the component identifier. Two standard optimizations — <strong>union by rank</strong> (always attach the shallower tree under the deeper one) and <strong>path compression</strong> (after a find, flatten the path to the root) — together give an amortized running time of 𝑂(𝛼(𝑛)) per operation, where 𝛼 is the famously slow-growing inverse Ackermann function. For any input you could ever build, 𝛼(𝑛) ≤ 4. In practice, treat it as a constant.</p><p>Union-Find has clever internals but a simple interface. You don’t need to know how it works to use it — with find and union, Kruskal&#39;s algorithm is complete.</p><h3>Complexity</h3><p>Where does the time go?</p><ul><li><strong>Sorting</strong> 𝑚 edges by weight: 𝑂(𝑚 log 𝑚).</li><li><strong>Union-Find operations</strong>: at most 2𝑚 finds and 𝑛 − 1 unions, each in 𝑂(𝛼(𝑛)) ≈ 𝑂(1) amortized.</li></ul><p>So the total running time is <strong>𝑂(𝑚 log 𝑚)</strong>, dominated entirely by the sort. Since 𝑚 ≤ 𝑛², we have 𝑂(𝑚 log 𝑚) = 𝑂(𝑚 log 𝑛), so you’ll see the complexity written either way.</p><p>For very dense graphs, an alternative MST algorithm — <strong>Prim’s algorithm</strong> — can be faster in practice because it never sorts all the edges. For sparse graphs and most real workloads, Kruskal’s is simple and fast enough.</p><h3>Where this matters</h3><p>The MST shows up across many applied domains. A few of the headliners:</p><h3>Single-linkage clustering</h3><p>Suppose you have a set of data points and a distance metric, and you want to group them into 𝑘 clusters. Build the complete graph on the points, with edge weights equal to the pairwise distances. Run Kruskal’s <em>almost to completion</em> — but stop after taking exactly 𝑛 − 𝑘 edges (instead of the full 𝑛 − 1). The result is a forest of exactly 𝑘 trees, and the 𝑘 vertex sets of those trees are your 𝑘 clusters.</p><p>Equivalently: build the full MST, then remove the 𝑘 − 1 heaviest edges. Each removal splits one component into two, so you end up with 𝑘 components.</p><p>Why does this give good clusters? Because the <em>latest</em> edges Kruskal adds are the longest — they bridge clusters that genuinely should be separate. Cutting them is the natural cluster boundary. This is exactly <strong>single-linkage hierarchical clustering</strong>, one of the classical clustering methods, expressed as an MST computation.</p><h3>Network design</h3><p>When telecom or utility companies plan a new network — fiber, water, electrical — connecting a set of locations, the MST is the natural starting point. It is the cheapest set of links that ensures everyone is reachable. Real networks add redundancy on top (extra edges so the network survives single failures), but the MST is the cost-minimal baseline that any design must beat to justify itself.</p><h3>Image segmentation</h3><p>Treat an image as a graph where each pixel is a vertex and edges connect neighbouring pixels with weight equal to the colour difference. Compute the MST. Then cut the heaviest edges — these are the ones between pixels of very different colour, i.e., across object boundaries. What remains is a partition of the image into regions of similar colour. This is the basis of the classical <strong>Felzenszwalb–Huttenlocher</strong> segmentation algorithm.</p><h3>Maze generation</h3><p>Take a grid graph (vertices = cells, edges = wall-removal options between adjacent cells), assign random weights, and compute the MST. The chosen edges describe which walls to remove; the un-chosen edges stay as walls. The resulting maze is guaranteed to be a tree — every cell reachable from every other, no loops, exactly one path between any two cells. This is one of the simplest maze-generation algorithms and produces visually pleasing mazes with one long “spine.”</p><h3>TSP approximations</h3><p>The minimum spanning tree gives a lower bound on the length of the optimal Travelling Salesman Problem tour, since any tour contains a spanning tree (just delete one edge). A more sophisticated construction — Christofides’ algorithm — uses an MST plus a minimum-weight matching to produce a tour at most 1.5× the optimal. The MST provides the foundation; the matching refines it.</p><h3>What to take away</h3><ul><li><strong>Greedy is sometimes provably correct.</strong> Kruskal’s looks like a heuristic — <em>take the lowest-weight edge, hope it works out</em> — but it does in fact find the MST. Every choice the algorithm makes is forced by structure.</li><li><strong>Sorting is the cost.</strong> When an algorithm is dominated by a sort, the rest of the work fades. Kruskal’s is “sort the edges and walk the list” — once you have sorted them, the algorithm is essentially linear.</li><li><strong>MSTs show up everywhere.</strong> Clustering, network design, image segmentation, maze generation, TSP bounds. When you need “connect everything as cheaply as possible,” reach for an MST.</li></ul><h3>Where to go next</h3><p>Now that you have seen the first weighted graph algorithm, the next two extend the idea in a different direction: instead of minimizing the total weight of a tree, minimize the <em>path length from a fixed source</em>.</p><ul><li><strong>Dijkstra’s Algorithm — Shortest Paths with Non-Negative Weights</strong> — BFS’s distance-ordered idea, generalized from edge counts to edge weights.</li><li><strong>Bellman-Ford — Shortest Paths When Weights Can Be Negative</strong> — what to do when even one edge has a negative weight, and Dijkstra’s settle-once strategy breaks.</li></ul><p>These articles are being published one at a time. The <a href="https://medium.com/p/5b3b90c16d54">hub article</a> keeps the full series map up to date. If you like learning visually, the <a href="https://www.youtube.com/@graphgarden">Graph Garden YouTube channel</a> has a video for each one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6cc211cbce6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four Graph Algorithms, Visualized — A Guided Tour]]></title>
            <link>https://medium.com/@mathchannel338/four-graph-algorithms-visualized-a-guided-tour-5b3b90c16d54?source=rss-fdc2523529c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b3b90c16d54</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[graph-theory]]></category>
            <dc:creator><![CDATA[Graph Garden]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 08:27:39 GMT</pubDate>
            <atom:updated>2026-07-22T04:53:12.136Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A guided tour of DFS, BFS, Kruskal’s, Dijkstra’s, and Bellman-Ford — what they solve, how they relate, and where to start.</em></p><p>Graphs are everywhere: road networks, social networks, dependency graphs, the web, even the grid your video-game character walks on. Algorithms are what make graphs useful, and out of the many that exist, this series picks the four that form the essential foundation.</p><p>We cover them in three parts: traversal first, then a greedy algorithm, and finally two algorithms for the shortest-path problem.</p><p>This article is the map — a short overview of how these algorithms relate to each other. Each algorithm also has its own deep-dive post, linked below. The <a href="https://www.youtube.com/@graphgarden"><strong>Graph Garden</strong></a> YouTube channel hosts companion videos for these algorithms — language-independent, with every concept shown on screen. They are designed to support your understanding visually, so do drop by if that sounds useful.</p><h3>What is a graph?</h3><p>If you have not seen graphs before — or if you’ve seen them only in passing — here is the quick orientation.</p><p>A <strong>graph</strong> is a collection of <strong>vertices</strong> (also called nodes — the dots) connected by <strong>edges</strong> (the lines). Anything you can model as “objects with connections between them” is a graph: cities and roads, people and friendships, web pages and hyperlinks, tasks and dependencies. The whole point of graph algorithms is that they let you reason about all of these in the same language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*fHrGs_06DiP1FNO52LCxzw.png" /><figcaption>Four kinds of graphs that appear in this series: undirected, directed, weighted, and weighted-with-negative</figcaption></figure><p>There are a few flavours, and which one you have shapes which algorithm applies:</p><ul><li><strong>Undirected.</strong> Edges have no direction — if 𝐴 is connected to 𝐵, that connection runs both ways. Friendships, roads in either direction. Used in MST problems.</li><li><strong>Directed.</strong> Edges have a direction — 𝐴 → 𝐵 doesn’t imply 𝐵 → 𝐴. Web links, task dependencies, one-way streets. Used in shortest-path problems below.</li><li><strong>Weighted.</strong> Each edge carries a number — a cost, distance, capacity. Road distance, currency exchange rate, link bandwidth. Required for the shortest-path and MST problems.</li><li><strong>Weighted with negative weights.</strong> Same, but the numbers can be negative — useful for “profit instead of cost” formulations, especially the currency-arbitrage application of Bellman-Ford.</li></ul><p>“Weighted” and “directed” are independent: a graph can be weighted-and-undirected (the typical MST setting), weighted-and-directed (the typical shortest-path setting), or either alone. The figure shows one example of each combination.</p><p>Throughout this series we use the standard notation: 𝐺 = (𝑉, 𝐸) is a graph with vertex set 𝑉 and edge set 𝐸. We write 𝑛 = |𝑉| for the number of vertices and 𝑚 = |𝐸| for the number of edges. Every running-time bound we quote will be in terms of 𝑛 and 𝑚.</p><h3>The four algorithms at a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XC8RW4rGZ2kzlhGUpTSCCw.png" /><figcaption>Four graph algorithms — at a glance: BFS, DFS, Kruskal’s, Dijkstra’s, Bellman-Ford, organized by problem type with generalization arrows</figcaption></figure><p>Three problems, four algorithms.</p><p><strong>Traversal</strong> is the warm-up: given a starting vertex, visit everything reachable from it. Two algorithms solve this, and they differ by exactly one line of code — one uses a queue, the other a stack. That single swap completely changes the order in which vertices are visited, which in turn opens up wildly different applications.</p><p><strong>The minimum spanning tree (MST) problem</strong> asks, given a weighted undirected graph, for a spanning tree whose total edge weight is minimum — where a <em>spanning tree</em> is a connected, acyclic subgraph that includes every vertex of the graph.</p><p><strong>The shortest-path problem</strong> asks, given a weighted directed graph together with a source and a target vertex, for a shortest path from the source to the target — that is, a path whose total edge weight is minimum.</p><p>Two well-known algorithms solve the shortest-path problem: <strong>Dijkstra’s algorithm</strong> and the <strong>Bellman-Ford algorithm</strong>. Dijkstra’s algorithm is faster than Bellman-Ford, but it cannot be applied to directed graphs with negative edge weights. Bellman-Ford, by contrast, can be applied even when negative weights are present.</p><p>The gold arrows in the diagram tell a story. <em>BFS finds shortest paths when every edge costs 1.</em> Add weights and you get <em>Dijkstra’s algorithm</em>. Add negative weights and you get the <em>Bellman-Ford algorithm</em>. Each step generalizes the problem, and the price is a slower algorithm.</p><h3>Reading order — pick one</h3><p>You can read these in any order, but if you’re learning the material for the first time, follow the educational flow. <em>Articles are published one at a time; this hub will be updated with the read-it link as each one goes live.</em></p><h4>1. DFS and BFS — How to Visit Everything in a Graph</h4><p>Same problem, same complexity, almost identical pseudocode — but BFS visits vertices in widening layers while DFS dives deep along one branch. We recommend reading this first; the rest of the series assumes you understand what “visiting a graph” means.</p><p><strong>Applications.</strong> BFS gives shortest paths in unweighted graphs (the unwitting start of the shortest-paths story). DFS detects cycles in directed graphs — what compilers, build systems, and spreadsheet engines all use to spot circular dependencies.</p><p>📄 <a href="https://medium.com/p/ad1743b24be1"><em>DFS vs BFS — deep dive</em> </a><br>🎥 <a href="https://youtu.be/qrtiaUyR7xA"><em>DFS vs BFS</em> on Graph Garden</a></p><h4>2. Kruskal’s Algorithm — Building the Cheapest Tree</h4><p>The first weighted graph algorithm. The pseudocode is just four lines and is simple to follow. The correctness argument — the <strong>cut property</strong> — is not too involved either, which is why we cover it in this series. Kruskal’s also introduces a fundamental supporting data structure: <strong>Union-Find</strong>, which checks “are these two vertices in the same component?” in essentially constant time.</p><p><strong>Where it shows up.</strong> Single-linkage clustering, telecom and utility network planning, image segmentation, maze generation, TSP approximations.</p><p>📄 <a href="https://medium.com/p/c6cc211cbce6"><em>Kruskal’s algorithm — deep dive</em></a><br>🎥 <a href="https://youtu.be/zpOI2epGKok"><em>Kruskal’s Algorithm — Visualized in 5 Minutes</em></a></p><h4>3. Dijkstra’s Algorithm — Shortest Paths with Non-Negative Weights</h4><p>Take BFS’s “visit in order of distance” idea and generalize it from edge counts to edge weights. The mechanical change is one data structure: a <em>priority queue</em> instead of a plain queue. The conceptual change is subtler: Dijkstra’s algorithm settles each vertex’s distance once and never reconsiders it. This strategy is only correct when all edge weights are non-negative.</p><p><strong>Where it shows up.</strong> Every car-navigation app, every link-state routing protocol, every game-AI pathfinder. If you’ve ever looked at a route on a map, you’ve used Dijkstra’s algorithm (or its heuristic-augmented sibling A*).</p><p>📄 <a href="https://medium.com/@mathchannel338/dijkstras-algorithm-shortest-paths-with-non-negative-weights-d6ac99e21e77"><em>Dijkstra’s algorithm — deep dive</em></a><br>🎥 <a href="https://youtu.be/0L0-_DGcyrY"><em>Dijkstra’s Algorithm — Visualized in 3 Minutes</em> on Graph Garden</a></p><h4>4. Bellman-Ford — Shortest Paths When Weights Can Be Negative</h4><p>When even a single edge has a negative weight, Dijkstra’s “settle a vertex and never reconsider it” strategy can break down. With negative-weight edges in the picture, it can happen that after a vertex’s distance is finalized, a longer detour through a negative edge turns out to have been cheaper. Bellman-Ford gives up on clever ordering and does the brute-force thing: scan every edge, 𝑛 − 1 times. After 𝑘 passes, every distance reachable in at most 𝑘 edges is correct. Bellman-Ford also lets you decide whether a negative cycle exists in the graph, and if one does, it can produce a concrete example of such a cycle. This further makes Bellman-Ford the algorithm of choice for currency-arbitrage detection in trading systems.</p><p>📄 <em>Bellman-Ford algorithm — deep dive</em> (coming soon)<br>🎥 <a href="https://youtu.be/k6CYbkXT-vY"><em>Bellman-Ford Algorithm — Visualized in 7 Minutes</em> on Graph Garden</a></p><h3>The Take-aways</h3><p>The full toolkit at a glance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dnm3glxv59RLe3ZyXJa2-Q.png" /><figcaption>The four algorithms at a glance: what problem each one solves, what kind of graph it needs, and how long it takes.</figcaption></figure><p>A few patterns to notice in this table.</p><p><strong>BFS, Dijkstra’s, and Bellman-Ford are one family.</strong> They all answer “shortest paths from a source,” in three different settings. Reading just the shortest-paths rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRe1Fce-rnD8ADkuYplA8g.png" /><figcaption>The same problem — single-source shortest paths — under three different settings. The price of generality is time.</figcaption></figure><p>The price of generality is time. When you can use BFS, use BFS. When weights are non-negative, use Dijkstra’s. Reach for Bellman-Ford only when you actually need to handle negative weights.</p><p><strong>Greedy choices show up in Kruskal’s and Dijkstra’s.</strong> Both algorithms use the <em>greedy</em> strategy of picking, at each step, the cheapest available option. Kruskal’s takes the smallest remaining edge that doesn’t form a cycle; Dijkstra’s settles the unvisited vertex with the smallest tentative distance. Bellman-Ford, the most general of the bunch, does not use a greedy strategy at all — it simply iterates until everything stabilizes.</p><p><strong>The right data structure makes the algorithm.</strong> Queue gives BFS. Stack gives DFS. Priority queue gives Dijkstra’s. Union-Find supports Kruskal’s. Pick the data structure that fits the job.</p><h3>Beyond these four</h3><p>This series covers four foundational algorithms, but there is more to explore beyond them. Some natural next steps:</p><ul><li><strong>Prim’s algorithm</strong> — another MST algorithm, structurally closer to Dijkstra’s than to Kruskal’s. The natural alternative answer to “build the cheapest tree.”</li><li><strong>A*</strong> — Dijkstra’s with a heuristic that tells it which direction to prefer. The standard for game AI and any pathfinding where you know roughly where the goal is.</li><li><strong>All-pairs shortest paths</strong> — what if you want distances between <em>every</em> pair of vertices, not just from one source? Floyd-Warshall and Johnson’s algorithm.</li><li><strong>Maximum matching</strong> — given a bipartite graph, pair up as many vertex pairs as possible. Hall’s theorem and the Hungarian algorithm.</li></ul><p>If you want more visualisations like these, the <a href="https://www.youtube.com/@graphgarden">Graph Garden YouTube channel</a> is where I post videos for graph algorithms and theorems.</p><p>Now pick an algorithm above and dive in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b3b90c16d54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DFS and BFS — How to Visit Everything in a Graph]]></title>
            <link>https://medium.com/@mathchannel338/dfs-and-bfs-how-to-visit-everything-in-a-graph-ad1743b24be1?source=rss-fdc2523529c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad1743b24be1</guid>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Graph Garden]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 08:26:23 GMT</pubDate>
            <atom:updated>2026-06-18T03:56:35.166Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The two foundational graph algorithms — same code, one data structure apart, completely different visit orders.</em></p><p><strong>Depth-first search (DFS)</strong> and <strong>breadth-first search (BFS)</strong> are the foundational traversal algorithms that other graph algorithms — Dijkstra’s, Kruskal’s, topological sort, cycle detection, connectivity — build on. Both solve the same simple problem: <em>visit every vertex reachable from a given starting vertex</em>. The mechanical difference between them is a single line of code — but that one line reorganizes the order in which vertices are visited, and that order is what makes the two algorithms useful for different things.</p><p>This article is the first in a <a href="https://medium.com/p/5b3b90c16d54">series on graph algorithms</a> (see the <a href="https://medium.com/p/5b3b90c16d54">hub</a> for the full map of the series).</p><p>A note on notation: throughout, 𝐺 = (𝑉, 𝐸) is a graph with vertex set 𝑉 and edge set 𝐸, where 𝑛 = |𝑉| and 𝑚 = |𝐸|.</p><blockquote><em>🎥 A companion video for this article is available on </em><a href="https://youtu.be/qrtiaUyR7xA"><em>Graph Garden</em></a><em>.</em></blockquote><h3>The problem</h3><p>Given an undirected graph 𝐺 and a starting vertex 𝑠, the goal is to visit every vertex reachable from 𝑠, exactly once each. No weights, no shortest paths — just visit everything. The only question is <em>in what order</em>.</p><p>The two well-known answers are BFS and DFS. They have the same complexity and nearly identical pseudocode, but the order in which they visit vertices is very different, and that order is what each algorithm is useful for. The mechanical difference between the two algorithms is a single data structure used to hold the vertices that have been discovered but not yet processed.</p><p>Before looking at any pseudocode, let us watch each algorithm in action on a small graph. The visual intuition makes the pseudocode much easier to read afterwards.</p><h3>Watching BFS</h3><p>The figure below shows BFS running on an 8-vertex graph from source 𝐴. Each panel shows one step of the algorithm. BFS keeps the discovered-but-not-yet-processed vertices in a <strong>queue</strong> — a container that releases items in the same order they were put in (first-in, first-out, or <strong>FIFO</strong>). The queue display at the bottom of each panel makes this visible: items leave from the left (the longest-waiting vertex pops first).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lakva0z4I0IXYpg_uVopug.png" /><figcaption>BFS step by step: a queue drains FIFO, layers grow outward</figcaption></figure><p>Pop 𝐴, enqueue its neighbors 𝐵 and 𝐶 — these form <em>layer 1</em>. <br>Pop 𝐵, enqueue 𝐷 and 𝐸. Pop 𝐶, enqueue 𝐹 and 𝐺. After step 3, all of layer 1 is settled and the entire layer 2 sits in the queue. Pop 𝐷, enqueue 𝐻 (the only vertex at layer 3). Then drain 𝐸, 𝐹, 𝐺, 𝐻 with no further additions. The traversal tree is short and bushy, as one would expect from an algorithm that explores all the close vertices first.</p><p>The key point: because the queue is FIFO, vertices closer to 𝑠 are always popped before vertices further away. BFS therefore visits the vertices <em>in order of distance from 𝑠</em>. This single property is what gives BFS its main applications.</p><h3>Watching DFS</h3><p>Now DFS on the same graph from the same source. The difference is the container that holds the discovered-but-not-yet-processed vertices: DFS uses a <strong>stack</strong> instead of a queue. A stack releases the <em>most recently</em> inserted item first (last-in, first-out, or <strong>LIFO</strong>). That small change completely reorganizes the visit order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inZ_L2p8w52R-_tS_eFLRQ.png" /><figcaption>DFS step by step: a stack drains LIFO, the algorithm dives deep before coming back up</figcaption></figure><p>Push 𝐴. From 𝐴 pick a neighbor 𝐵 and push. From 𝐵 pick 𝐷, push. From 𝐷 pick 𝐻, push — and now 𝐻 is a leaf with no unvisited neighbors. Pop until we reach 𝐵 again, then dive into 𝐸 and 𝐺. From 𝐺, the unvisited vertex 𝐶 is reached not directly from 𝐴 but via the longer detour 𝐴 → 𝐵 → 𝐸 → 𝐺 → 𝐶. Finally from 𝐶 we visit 𝐹. The traversal tree is long and stringy: DFS follows one branch as far as it goes before coming back to try another.</p><p>The key point: because the stack is LIFO, the most recently discovered vertex is always processed next. DFS therefore <em>dives deep</em> along a single branch before it ever backtracks. This depth-diving behaviour is what gives DFS its main applications.</p><h3>The pseudocode: one template, two algorithms</h3><p>With both visit orders seen on a concrete example, the unified pseudocode is now easy to read. The container holding discovered-but-not-yet-processed vertices is commonly called the <strong>frontier</strong> — for example, the vertices 𝐵 and 𝐶 after step 1 of the BFS run above are exactly the frontier at that moment. The single difference between BFS and DFS is whether the frontier is implemented as a queue or as a stack.</p><pre>visited ← {𝑠}<br>frontier ← {𝑠}            # queue for BFS, stack for DFS<br>while frontier is not empty:<br>    𝑣 ← take one out of frontier<br>    for each neighbor 𝑤 of 𝑣:<br>        if 𝑤 ∉ visited:<br>            mark 𝑤 visited<br>            put 𝑤 into frontier</pre><p>Swap “queue” for “stack” and BFS becomes DFS. In practice, DFS is usually written recursively — dfs(𝑣) = mark 𝑣 visited; for each unvisited neighbor 𝑤: dfs(𝑤) — but the call stack of the recursion <em>is</em> the stack. The same data structure is used; it is simply managed by the language runtime instead of by the programmer.</p><p>The word <strong>frontier</strong> is not standard textbook terminology, but it is a useful mental model: the set of vertices that have been <em>seen</em> but not yet <em>expanded</em>. Almost every graph algorithm has a frontier of some kind, and the choice of data structure for the frontier is what distinguishes the algorithms. The same picture will return with Dijkstra’s algorithm (where the frontier is a priority queue) and with Kruskal’s algorithm (where the “frontier” is the sorted list of edges).</p><h3>Complexity</h3><p>Both BFS and DFS run in <strong>𝑂(𝑛 + 𝑚)</strong> time. Each vertex is pushed onto and popped from the frontier exactly once, which takes 𝑂(𝑛) time in total. Each edge is examined at most twice — once from each of its endpoints — which takes 𝑂(𝑚) time in total. Summing the two gives 𝑂(𝑛 + 𝑚), which is linear in the size of the graph. This bound cannot be improved upon, because reading the graph itself already requires Ω(𝑛 + 𝑚) time.</p><h3>Application 1 — BFS gives shortest paths in unweighted graphs</h3><p>Because BFS visits vertices in order of distance from 𝑠, the moment it first reaches a vertex 𝑣, the path that got it there is a shortest path from 𝑠 to 𝑣. Moreover, if every time a vertex 𝑤 is enqueued from a neighbor 𝑣 we record 𝑣 as the parent of 𝑤 (𝑝(𝑤) = 𝑣), then the parent pointers collectively form a <strong>shortest-path tree</strong> rooted at 𝑠. The shortest path from 𝑠 to any vertex 𝑥 can be recovered by walking parent pointers back: 𝑥 → 𝑝(𝑥) → 𝑝(𝑝(𝑥)) → ⋯ → 𝑠.</p><p>BFS is therefore the appropriate algorithm whenever “distance” means “number of edges”. A few common examples:</p><ul><li><strong>Sliding puzzles of small size.</strong> For an 8-puzzle (3×3) or smaller, every legal move changes the board into one of a small set of neighboring states, so the configurations form an unweighted graph and BFS finds the optimal sequence of moves. For the 15-puzzle and larger, the state space becomes too large for BFS in practice, and heuristic search such as A* or IDA* is used instead.</li><li><strong>Word ladders.</strong> Given two words of the same length, find the shortest sequence of single-letter substitutions through valid intermediate words. The words form the vertices of an unweighted graph, and BFS gives the minimum number of substitutions.</li><li><strong>Social-network hops.</strong> In an unweighted social-network graph, BFS computes the minimum number of friendship links between two users.</li></ul><p>Once edge weights become non-uniform, BFS is no longer sufficient. Dijkstra’s algorithm can be viewed as the natural generalization of BFS to weighted edges, and the Bellman-Ford algorithm as a further generalization to graphs that may contain negative weights.</p><h3>Application 2 — DFS detects cycles in directed graphs</h3><p>DFS is useful when the structure of the graph, rather than distances, is what matters. The canonical example is cycle detection in directed graphs.</p><p>The idea is to classify each vertex into one of three states during the DFS:</p><ul><li><strong>white</strong> — not yet visited,</li><li><strong>gray</strong> — currently on the recursion stack (DFS has entered this vertex but has not yet returned from it),</li><li><strong>black</strong> — fully processed (DFS has entered, finished, and returned).</li></ul><p>Run DFS. Each time an edge 𝑢 → 𝑣 is examined:</p><ul><li>If 𝑣 is white, recurse into it (this is a normal <em>tree edge</em>).</li><li>If 𝑣 is <strong>gray</strong>, then 𝑢 → 𝑣 is a <strong>back edge</strong>, and the graph contains a cycle. This is because 𝑣 is still on the recursion stack, so there is an active DFS path from 𝑣 down through other gray vertices to 𝑢. Adding the edge 𝑢 → 𝑣 closes that path into a cycle.</li><li>If 𝑣 is black, the edge can be ignored: 𝑣 belongs to a subtree that has already been fully processed, so following 𝑢 → 𝑣 cannot create a cycle through the current recursion stack.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WK4elMZKBXMeG4JLPq72Q.png" /><figcaption>DFS detects a cycle when it tries to enter a vertex that is still on the recursion stack</figcaption></figure><p>Step 1: DFS starts at vertex 1 and pushes it onto the stack (gray). Steps 2–4: the algorithm dives 1 → 2 → 3 → 4 → 5 → 6 → 8, marking each vertex gray as it enters. The recursion stack now holds seven vertices in order. Step 5: from 8, the algorithm examines the edge 8 → 2. Vertex 2 is <strong>still gray</strong> — its DFS call has not yet returned — so 8 → 2 is a back edge, and 2 → 3 → 4 → 5 → 6 → 8 → 2 is a cycle. Step 6: after backtracking, the algorithm visits the remaining vertex 7 via 1 → 7, then unwinds; every vertex ends up black.</p><p>Cycle detection in directed graphs is used in real systems to detect circular dependencies:</p><ul><li><strong>Compilers</strong> check that there are no circular module imports — if A imports B which imports A, the compile order is undefined.</li><li><strong>Build systems</strong> such as make and Bazel rely on the dependency graph being acyclic to determine a build order; if there is a cycle, no valid order exists.</li><li><strong>Spreadsheet engines</strong> detect circular cell references (A1 = B1 + 1, B1 = A1 + 1) by the same method.</li><li><strong>Task schedulers</strong> and <strong>database migration tools</strong> use the absence of cycles to compute a <em>topological sort</em> — a linear order respecting all dependencies.</li></ul><p>A small variation on plain DFS thus yields a fundamental structural fact about the graph.</p><h3>Take-aways</h3><ul><li><strong>Same algorithm, swapped data structure.</strong> BFS and DFS share their pseudocode and differ only in queue versus stack. Many graph algorithms that appear later in this series can be viewed as “BFS with a different frontier”: Dijkstra’s algorithm replaces the queue with a priority queue, and the Bellman-Ford algorithm abandons the frontier altogether and relies on edge passes instead.</li><li><strong>Order matters.</strong> BFS visits vertices in widening layers and therefore naturally computes shortest paths in unweighted graphs. DFS dives deep along one branch and therefore naturally tracks the recursion structure and finds back edges. The choice between BFS and DFS depends on which order matches the problem at hand.</li><li><strong>𝑂(𝑛 + 𝑚) is the ceiling.</strong> Any algorithm that traverses a graph at least once costs Ω(𝑛 + 𝑚), so BFS and DFS are optimal for the problem of visiting everything. Algorithms that take more time than this are paying for additional structure (distances, MSTs, paths).</li></ul><h3>Where to go next</h3><p>With traversal in hand, the rest of the series adds weights to edges and asks more demanding questions:</p><ul><li><strong>Kruskal’s Algorithm — Building the Cheapest Tree.</strong> The first weighted graph algorithm. A four-line greedy procedure for minimum spanning trees.</li><li><strong>Dijkstra’s Algorithm — Shortest Paths with Non-Negative Weights.</strong> BFS’s distance-ordered idea, generalized from edge counts to edge weights.</li><li><strong>Bellman-Ford — Shortest Paths When Weights Can Be Negative.</strong> What to do when even a single edge has a negative weight, and Dijkstra’s settle-once strategy can break down.</li></ul><p>These articles are being published one at a time. The <a href="https://medium.com/p/5b3b90c16d54">hub article</a> keeps the full series map up to date. Companion videos for each algorithm are available on the <a href="https://www.youtube.com/@graphgarden">Graph Garden YouTube channel</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad1743b24be1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>