<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ graphs - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ graphs - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 23 Jun 2026 22:44:57 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/graphs/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Graph Algorithms in Python: BFS, DFS, and Beyond ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever wondered how Google Maps finds the fastest route or how Netflix recommends what to watch? Graph algorithms are behind these decisions. Graphs, made up of nodes (points) and edges (connections), are one of the most powerful data structur... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/graph-algorithms-in-python-bfs-dfs-and-beyond/</link>
                <guid isPermaLink="false">68b86be0956e509211153b48</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ graphs ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oyedele Tioluwani ]]>
                </dc:creator>
                <pubDate>Wed, 03 Sep 2025 16:25:04 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756916679855/9b173128-ed79-4ae0-8cc8-79fca17662dd.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever wondered how Google Maps finds the fastest route or how Netflix recommends what to watch? Graph algorithms are behind these decisions.</p>
<p>Graphs, made up of nodes (points) and edges (connections), are one of the most powerful data structures in computer science. They help model relationships efficiently, from social networks to transportation systems.</p>
<p>In this guide, we will explore two core traversal techniques: Breadth-First Search (BFS) and Depth-First Search (DFS). Moving on from there, we will cover advanced algorithms like Dijkstra’s, A*, Kruskal’s, Prim’s, and Bellman-Ford.</p>
<h3 id="heading-table-of-contents">Table of Contents:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-understanding-graphs-in-python">Understanding Graphs in Python</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ways-to-represent-graphs-in-python">Ways to Represent Graphs in Python</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-breadth-first-search-bfs">Breadth-First Search (BFS)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-depth-first-search-dfs">Depth-First Search (DFS)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-dijkstras-algorithm">Dijkstra’s Algorithm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-search">A* Search</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-kruskals-algorithm">Kruskal’s Algorithm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-prims-algorithm">Prim’s Algorithm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-bellman-ford-algorithm">Bellman-Ford Algorithm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-optimizing-graph-algorithms-in-python">Optimizing Graph Algorithms in Python</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-takeaways">Key Takeaways</a></p>
</li>
</ol>
<h2 id="heading-understanding-graphs-in-python">Understanding Graphs in Python</h2>
<p>A graph consists of <strong>nodes (vertices)</strong> and <strong>edges (relationships)</strong>.</p>
<p>For examples, in a social network, people are nodes and friendships are edges. Or in a roadmap, cities are nodes and roads are edges.</p>
<p>There are a few different types of graphs:</p>
<ul>
<li><p><strong>Directed</strong>: edges have direction (one-way streets, task scheduling).</p>
</li>
<li><p><strong>Undirected</strong>: edges go both ways (mutual friendships).</p>
</li>
<li><p><strong>Weighted</strong>: edges have values (distances, costs).</p>
</li>
<li><p><strong>Unweighted</strong>: edges are equal (basic subway routes).</p>
</li>
</ul>
<p>Now that you know what graphs are, let’s look at the different ways they can be represented in Python.</p>
<h2 id="heading-ways-to-represent-graphs-in-python">Ways to Represent Graphs in Python</h2>
<p>Before diving into traversal and pathfinding, it’s important to know how graphs can be represented. Different problems call for different representations.</p>
<h3 id="heading-adjacency-matrix">Adjacency Matrix</h3>
<p>An adjacency matrix is a 2D array where each cell <code>(i, j)</code> shows whether there is an edge from node <code>i</code> to node <code>j</code>.</p>
<ul>
<li><p>In an <strong>unweighted graph</strong>, <code>0</code> means no edge, and <code>1</code> means an edge exists.</p>
</li>
<li><p>In a <strong>weighted graph</strong>, the cell holds the edge weight.</p>
</li>
</ul>
<p>This makes it very quick to check if two nodes are directly connected (constant-time lookup), but it uses more memory for large graphs.</p>
<pre><code class="lang-python">graph = [
    [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>],
    [<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>],
    [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>]
]
</code></pre>
<p>Here, the matrix shows a fully connected graph of 3 nodes. For example, <code>graph[0][1] = 1</code> means there is an edge from node 0 to node 1.</p>
<h3 id="heading-adjacency-list">Adjacency List</h3>
<p>An adjacency list represents each node along with the list of nodes it connects to.</p>
<p>This is usually more efficient for sparse graphs (where not every node is connected to every other node). It saves memory because only actual edges are stored instead of an entire grid.</p>
<pre><code class="lang-python">graph = {
    <span class="hljs-string">'A'</span>: [<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>],
    <span class="hljs-string">'B'</span>: [<span class="hljs-string">'A'</span>,<span class="hljs-string">'C'</span>],
    <span class="hljs-string">'C'</span>: [<span class="hljs-string">'A'</span>,<span class="hljs-string">'B'</span>]
}
</code></pre>
<p>Here, node <code>A</code> connects to <code>B</code> and <code>C</code>, and so on. Checking connections takes a little longer than with a matrix, but for large, sparse graphs, it’s the better option.</p>
<h3 id="heading-using-networkx">Using NetworkX</h3>
<p>When working on real-world applications, writing your own adjacency lists and matrices can get tedious. That’s where <strong>NetworkX</strong> comes in, a Python library that simplifies graph creation and analysis.</p>
<p>With just a few lines of code, you can build graphs, visualize them, and run advanced algorithms without reinventing the wheel.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> networkx <span class="hljs-keyword">as</span> nx
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt

G = nx.Graph()
G.add_edges_from([(<span class="hljs-string">'A'</span>,<span class="hljs-string">'B'</span>), (<span class="hljs-string">'A'</span>,<span class="hljs-string">'C'</span>), (<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>)])
nx.draw(G, with_labels=<span class="hljs-literal">True</span>)
plt.show()
</code></pre>
<p>This builds a triangle-shaped graph with nodes A, B, and C. NetworkX also lets you easily run algorithms like shortest paths or spanning trees without manually coding them.</p>
<p>Now that we’ve seen different ways to represent graphs, let’s move on to traversal methods, starting with Breadth-First Search (BFS).</p>
<h2 id="heading-breadth-first-search-bfs">Breadth-First Search (BFS)</h2>
<p>The basic idea behind BFS is to explore a graph one layer at a time. It looks at all the neighbors of a starting node before moving on to the next level. A queue is used to keep track of what comes next.</p>
<p>BFS is particularly useful for:</p>
<ul>
<li><p>Finding the shortest path in unweighted graphs</p>
</li>
<li><p>Detecting connected components</p>
</li>
<li><p>Crawling web pages</p>
</li>
</ul>
<p>Here’s an example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> deque

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bfs</span>(<span class="hljs-params">graph, start</span>):</span>
    visited = {start}
    queue = deque([start])

    <span class="hljs-keyword">while</span> queue:
        node = queue.popleft()
        print(node, end=<span class="hljs-string">" "</span>)
        <span class="hljs-keyword">for</span> neighbor <span class="hljs-keyword">in</span> graph[node]:
            <span class="hljs-keyword">if</span> neighbor <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> visited:
                visited.add(neighbor)
                queue.append(neighbor)


graph = {
    <span class="hljs-string">'A'</span>: [<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>],
    <span class="hljs-string">'B'</span>: [<span class="hljs-string">'A'</span>,<span class="hljs-string">'D'</span>,<span class="hljs-string">'E'</span>],
    <span class="hljs-string">'C'</span>: [<span class="hljs-string">'A'</span>,<span class="hljs-string">'F'</span>],
    <span class="hljs-string">'D'</span>: [<span class="hljs-string">'B'</span>],
    <span class="hljs-string">'E'</span>: [<span class="hljs-string">'B'</span>,<span class="hljs-string">'F'</span>],
    <span class="hljs-string">'F'</span>: [<span class="hljs-string">'C'</span>,<span class="hljs-string">'E'</span>]
}

bfs(graph, <span class="hljs-string">'A'</span>)
</code></pre>
<p>Here’s what’s going on in this code:</p>
<ul>
<li><p><code>graph</code> is a dict where each node maps to a list of neighbors.</p>
</li>
<li><p><code>deque</code> is used as a FIFO queue so we visit nodes level-by-level.</p>
</li>
<li><p><code>visited</code> keeps track of nodes we’ve already processed so we don’t loop forever on cycles.</p>
</li>
<li><p>In the loop, we pop a node, print it, then for each unvisited neighbor, we mark it visited and enqueue it.</p>
</li>
</ul>
<p>And here’s the output:</p>
<pre><code class="lang-python">A B C D E F
</code></pre>
<p>Now that we have seen how BFS works, let’s turn to its counterpart: Depth-First Search (DFS).</p>
<h2 id="heading-depth-first-search-dfs">Depth-First Search (DFS)</h2>
<p>DFS works differently from BFS. Instead of moving level by level, it follows one path as far as it can go before backtracking. Think of it as diving deep down a trail, then returning to explore the others.</p>
<p>We can implement DFS in two ways:</p>
<ul>
<li><p><strong>Recursive DFS</strong>, which uses the function call stack</p>
</li>
<li><p><strong>Iterative DFS</strong>, which uses an explicit stack</p>
</li>
</ul>
<p>DFS is especially useful for:</p>
<ul>
<li><p>Cycle detection</p>
</li>
<li><p>Maze solving and puzzles</p>
</li>
<li><p>Topological sorting</p>
</li>
</ul>
<p>Here’s an example of recursive DFS:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dfs_recursive</span>(<span class="hljs-params">graph, node, visited=None</span>):</span>
    <span class="hljs-keyword">if</span> visited <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
        visited = set()
    <span class="hljs-keyword">if</span> node <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> visited:
        print(node, end=<span class="hljs-string">" "</span>)
        visited.add(node)
        <span class="hljs-keyword">for</span> neighbor <span class="hljs-keyword">in</span> graph[node]:
            dfs_recursive(graph, neighbor, visited)

graph = {
    <span class="hljs-string">'A'</span>: [<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>],
    <span class="hljs-string">'B'</span>: [<span class="hljs-string">'A'</span>,<span class="hljs-string">'D'</span>,<span class="hljs-string">'E'</span>],
    <span class="hljs-string">'C'</span>: [<span class="hljs-string">'A'</span>,<span class="hljs-string">'F'</span>],
    <span class="hljs-string">'D'</span>: [<span class="hljs-string">'B'</span>],
    <span class="hljs-string">'E'</span>: [<span class="hljs-string">'B'</span>,<span class="hljs-string">'F'</span>],
    <span class="hljs-string">'F'</span>: [<span class="hljs-string">'C'</span>,<span class="hljs-string">'E'</span>]
}

dfs_recursive(graph, <span class="hljs-string">'A'</span>)
</code></pre>
<ul>
<li><p><code>visited</code> is a set that tracks nodes already processed so you don’t loop forever on cycles.</p>
</li>
<li><p>On each call, if <code>node</code> hasn’t been seen, it’s printed, marked visited, then the function recurses into each neighbor.</p>
</li>
</ul>
<p>Traversal order:</p>
<pre><code class="lang-python">A B D E F C
</code></pre>
<p>Explanation: DFS visits B after A, goes deeper into D, then backtracks to explore E and F, and finally visits C.</p>
<p>And here’s an example of iterative DFS:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dfs_iterative</span>(<span class="hljs-params">graph, start</span>):</span>
    visited = set()
    stack = [start]

    <span class="hljs-keyword">while</span> stack:
        node = stack.pop()
        <span class="hljs-keyword">if</span> node <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> visited:
            print(node, end=<span class="hljs-string">" "</span>)
            visited.add(node)
            stack.extend(reversed(graph[node]))

dfs_iterative(graph, <span class="hljs-string">'A'</span>)
</code></pre>
<ul>
<li><p><code>visited</code> tracks nodes you’ve already processed so you don’t loop on cycles.</p>
</li>
<li><p><code>stack</code> is LIFO (last in, first out) – you <code>pop()</code> the top node, process it, then push its neighbors.</p>
</li>
<li><p><code>reversed(graph[node])</code> pushes neighbors in reverse so they’re visited in the original left-to-right order (mimicking the usual recursive DFS).</p>
</li>
</ul>
<p>Here’s the output:</p>
<pre><code class="lang-python">A B D E F C
</code></pre>
<p>With BFS and DFS explained, we can now move on to algorithms that solve more complex problems, starting with Dijkstra’s shortest path algorithm.</p>
<h2 id="heading-dijkstras-algorithm">Dijkstra’s Algorithm</h2>
<p>Dijkstra’s algorithm is built on a simple rule: always visit the node with the smallest known distance first. By repeating this, it uncovers the shortest path from a starting node to all others in a weighted graph that doesn’t have negative edges.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> heapq

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dijkstra</span>(<span class="hljs-params">graph, start</span>):</span>
    heap = [(<span class="hljs-number">0</span>, start)]
    shortest_path = {node: float(<span class="hljs-string">'inf'</span>) <span class="hljs-keyword">for</span> node <span class="hljs-keyword">in</span> graph}
    shortest_path[start] = <span class="hljs-number">0</span>

    <span class="hljs-keyword">while</span> heap:
        cost, node = heapq.heappop(heap)
        <span class="hljs-keyword">for</span> neighbor, weight <span class="hljs-keyword">in</span> graph[node]:
            new_cost = cost + weight
            <span class="hljs-keyword">if</span> new_cost &lt; shortest_path[neighbor]:
                shortest_path[neighbor] = new_cost
                heapq.heappush(heap, (new_cost, neighbor))
    <span class="hljs-keyword">return</span> shortest_path

graph = {
    <span class="hljs-string">'A'</span>: [(<span class="hljs-string">'B'</span>,<span class="hljs-number">1</span>), (<span class="hljs-string">'C'</span>,<span class="hljs-number">4</span>)],
    <span class="hljs-string">'B'</span>: [(<span class="hljs-string">'A'</span>,<span class="hljs-number">1</span>), (<span class="hljs-string">'C'</span>,<span class="hljs-number">2</span>), (<span class="hljs-string">'D'</span>,<span class="hljs-number">5</span>)],
    <span class="hljs-string">'C'</span>: [(<span class="hljs-string">'A'</span>,<span class="hljs-number">4</span>), (<span class="hljs-string">'B'</span>,<span class="hljs-number">2</span>), (<span class="hljs-string">'D'</span>,<span class="hljs-number">1</span>)],
    <span class="hljs-string">'D'</span>: [(<span class="hljs-string">'B'</span>,<span class="hljs-number">5</span>), (<span class="hljs-string">'C'</span>,<span class="hljs-number">1</span>)]
}

print(dijkstra(graph, <span class="hljs-string">'A'</span>))
</code></pre>
<p>Here’s what’s going on in this code:</p>
<ul>
<li><p><code>graph</code> is an adjacency list: each node maps to a list of <code>(neighbor, weight)</code> pairs.</p>
</li>
<li><p><code>shortest_path</code> stores the current best-known distance to each node (∞ initially, 0 for <code>start</code>).</p>
</li>
<li><p><code>heap</code> (priority queue) holds frontier nodes as <code>(cost, node)</code>, always popping the smallest cost first.</p>
</li>
<li><p>For each popped <code>node</code>, it relaxes its edges: for each <code>(neighbor, weight)</code>, compute <code>new_cost</code>. If <code>new_cost</code> beats <code>shortest_path[neighbor]</code>, update it and push the neighbor with that cost.</p>
</li>
</ul>
<p>And here’s the output:</p>
<pre><code class="lang-python">{<span class="hljs-string">'A'</span>: <span class="hljs-number">0</span>, <span class="hljs-string">'B'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'C'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'D'</span>: <span class="hljs-number">4</span>}
</code></pre>
<p>Moving on, let’s look at an extension of this algorithm: <em>A Search.</em>*</p>
<h2 id="heading-a-search">A* Search</h2>
<p>A* works like Dijkstra’s but adds a heuristic function that estimates how close a node is to the goal. This makes it more efficient by guiding the search in the right direction.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> heapq

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">heuristic</span>(<span class="hljs-params">node, goal</span>):</span>
    heuristics = {<span class="hljs-string">'A'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'B'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'C'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'D'</span>: <span class="hljs-number">0</span>}
    <span class="hljs-keyword">return</span> heuristics.get(node, <span class="hljs-number">0</span>)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a_star</span>(<span class="hljs-params">graph, start, goal</span>):</span>
    g_costs = {node: float(<span class="hljs-string">'inf'</span>) <span class="hljs-keyword">for</span> node <span class="hljs-keyword">in</span> graph}
    g_costs[start] = <span class="hljs-number">0</span>
    came_from = {}

    heap = [(heuristic(start, goal), start)]

    <span class="hljs-keyword">while</span> heap:
        f, node = heapq.heappop(heap)

        <span class="hljs-keyword">if</span> f &gt; g_costs[node] + heuristic(node, goal):
            <span class="hljs-keyword">continue</span>

        <span class="hljs-keyword">if</span> node == goal:
            path = [node]
            <span class="hljs-keyword">while</span> node <span class="hljs-keyword">in</span> came_from:
                node = came_from[node]
                path.append(node)
            <span class="hljs-keyword">return</span> path[::<span class="hljs-number">-1</span>], g_costs[path[<span class="hljs-number">0</span>]]

        <span class="hljs-keyword">for</span> neighbor, weight <span class="hljs-keyword">in</span> graph[node]:
            new_g = g_costs[node] + weight
            <span class="hljs-keyword">if</span> new_g &lt; g_costs[neighbor]:
                g_costs[neighbor] = new_g
                came_from[neighbor] = node
                heapq.heappush(heap, (new_g + heuristic(neighbor, goal), neighbor))

    <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>, float(<span class="hljs-string">'inf'</span>)

graph = {
    <span class="hljs-string">'A'</span>: [(<span class="hljs-string">'B'</span>,<span class="hljs-number">1</span>), (<span class="hljs-string">'C'</span>,<span class="hljs-number">4</span>)],
    <span class="hljs-string">'B'</span>: [(<span class="hljs-string">'A'</span>,<span class="hljs-number">1</span>), (<span class="hljs-string">'C'</span>,<span class="hljs-number">2</span>), (<span class="hljs-string">'D'</span>,<span class="hljs-number">5</span>)],
    <span class="hljs-string">'C'</span>: [(<span class="hljs-string">'A'</span>,<span class="hljs-number">4</span>), (<span class="hljs-string">'B'</span>,<span class="hljs-number">2</span>), (<span class="hljs-string">'D'</span>,<span class="hljs-number">1</span>)],
    <span class="hljs-string">'D'</span>: []
}

print(a_star(graph, <span class="hljs-string">'A'</span>, <span class="hljs-string">'D'</span>))
</code></pre>
<p>This one’s a little more complex, so here’s what’s going on:</p>
<ul>
<li><p><code>graph</code>: adjacency list – each node maps to <code>[(neighbor, weight), ...]</code>.</p>
</li>
<li><p><code>heuristic(node, goal)</code>: returns an estimate <code>h(node)</code> (lower is better). It’s passed <code>goal</code> but in this demo uses a fixed dict.</p>
</li>
<li><p><code>g_costs</code>: best known cost from <code>start</code> to each node (∞ initially, 0 for start).</p>
</li>
<li><p><code>heap</code>: min-heap of <code>(priority, node)</code> where <code>priority = g + h</code>.</p>
</li>
<li><p><code>came_from</code>: backpointers to reconstruct the path once we pop the goal.</p>
</li>
</ul>
<p>Then in the main loop:</p>
<ul>
<li><p>We pop the node with smallest priority.</p>
</li>
<li><p>If it’s the goal, we backtrack via <code>came_from</code> to build the path and return it with <code>g_costs[goal]</code>.</p>
</li>
<li><p>Otherwise, we relax the edges: for each <code>(neighbor, weight)</code>, compute <code>new_cost = g_costs[node] + weight</code>. If <code>new_cost</code> improves <code>g_costs[neighbor]</code>, update it, set <code>came_from[neighbor] = node</code>, and push <code>(new_cost + heuristic(neighbor, goal), neighbor)</code>.</p>
</li>
</ul>
<p>Output:</p>
<pre><code class="lang-python">([<span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-string">'D'</span>], <span class="hljs-number">4</span>)
</code></pre>
<p>Next up, let’s move from shortest paths to spanning trees. This is where Kruskal’s algorithm comes in.</p>
<h2 id="heading-kruskals-algorithm">Kruskal’s Algorithm</h2>
<p>Kruskal’s algorithm builds a Minimum Spanning Tree (MST) by sorting all edges from smallest to largest and adding them one at a time, as long as they don’t create a cycle. This makes it a greedy algorithm as it always picks the cheapest option available at each step.</p>
<p>The implementation uses a Disjoint Set (Union-Find) data structure to efficiently check whether adding an edge would create a cycle. Each node starts in its own set, and as edges are added, sets are merged.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DisjointSet</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, nodes</span>):</span>
        self.parent = {node: node <span class="hljs-keyword">for</span> node <span class="hljs-keyword">in</span> nodes}
        self.rank = {node: <span class="hljs-number">0</span> <span class="hljs-keyword">for</span> node <span class="hljs-keyword">in</span> nodes}
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">find</span>(<span class="hljs-params">self, node</span>):</span>
        <span class="hljs-keyword">if</span> self.parent[node] != node:
            self.parent[node] = self.find(self.parent[node])
        <span class="hljs-keyword">return</span> self.parent[node]
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">union</span>(<span class="hljs-params">self, node1, node2</span>):</span>
        r1, r2 = self.find(node1), self.find(node2)
        <span class="hljs-keyword">if</span> r1 != r2:
            <span class="hljs-keyword">if</span> self.rank[r1] &gt; self.rank[r2]:
                self.parent[r2] = r1
            <span class="hljs-keyword">else</span>:
                self.parent[r1] = r2
                <span class="hljs-keyword">if</span> self.rank[r1] == self.rank[r2]:
                    self.rank[r2] += <span class="hljs-number">1</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">kruskal</span>(<span class="hljs-params">graph</span>):</span>
    edges = sorted(graph, key=<span class="hljs-keyword">lambda</span> x: x[<span class="hljs-number">2</span>])
    mst, ds = [], DisjointSet({u <span class="hljs-keyword">for</span> e <span class="hljs-keyword">in</span> graph <span class="hljs-keyword">for</span> u <span class="hljs-keyword">in</span> e[:<span class="hljs-number">2</span>]})
    <span class="hljs-keyword">for</span> u,v,w <span class="hljs-keyword">in</span> edges:
        <span class="hljs-keyword">if</span> ds.find(u) != ds.find(v):
            ds.union(u,v)
            mst.append((u,v,w))
    <span class="hljs-keyword">return</span> mst

graph = [(<span class="hljs-string">'A'</span>,<span class="hljs-string">'B'</span>,<span class="hljs-number">1</span>), (<span class="hljs-string">'A'</span>,<span class="hljs-string">'C'</span>,<span class="hljs-number">4</span>), (<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>,<span class="hljs-number">2</span>), (<span class="hljs-string">'B'</span>,<span class="hljs-string">'D'</span>,<span class="hljs-number">5</span>), (<span class="hljs-string">'C'</span>,<span class="hljs-string">'D'</span>,<span class="hljs-number">1</span>)]
print(kruskal(graph))
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">[(<span class="hljs-string">'A'</span>,<span class="hljs-string">'B'</span>,<span class="hljs-number">1</span>), (<span class="hljs-string">'C'</span>,<span class="hljs-string">'D'</span>,<span class="hljs-number">1</span>), (<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>,<span class="hljs-number">2</span>)]
</code></pre>
<p>Here, the MST includes the smallest edges that connect all nodes without forming cycles. Now that we have seen Kruskal’s, we can move further to analyze another algorithm.</p>
<h2 id="heading-prims-algorithm">Prim’s Algorithm</h2>
<p>Prim’s algorithm also finds an MST, but it grows the tree step by step. It starts with one node and repeatedly <strong>adds the smallest edge</strong> that connects the current tree to a new node. Think of it as expanding a connected “island” until all nodes are included.</p>
<p>This implementation uses a <strong>priority queue (heapq)</strong> to always select the smallest available edge efficiently.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> heapq

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">prim</span>(<span class="hljs-params">graph, start</span>):</span>
    mst, visited = [], {start}
    edges = [(w, start, n) <span class="hljs-keyword">for</span> n,w <span class="hljs-keyword">in</span> graph[start]]
    heapq.heapify(edges)

    <span class="hljs-keyword">while</span> edges:
        w,u,v = heapq.heappop(edges)
        <span class="hljs-keyword">if</span> v <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> visited:
            visited.add(v)
            mst.append((u,v,w))
            <span class="hljs-keyword">for</span> n,w <span class="hljs-keyword">in</span> graph[v]:
                <span class="hljs-keyword">if</span> n <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> visited:
                    heapq.heappush(edges, (w,v,n))
    <span class="hljs-keyword">return</span> mst

graph = {
    <span class="hljs-string">'A'</span>:[(<span class="hljs-string">'B'</span>,<span class="hljs-number">1</span>),(<span class="hljs-string">'C'</span>,<span class="hljs-number">4</span>)],
    <span class="hljs-string">'B'</span>:[(<span class="hljs-string">'A'</span>,<span class="hljs-number">1</span>),(<span class="hljs-string">'C'</span>,<span class="hljs-number">2</span>),(<span class="hljs-string">'D'</span>,<span class="hljs-number">5</span>)],
    <span class="hljs-string">'C'</span>:[(<span class="hljs-string">'A'</span>,<span class="hljs-number">4</span>),(<span class="hljs-string">'B'</span>,<span class="hljs-number">2</span>),(<span class="hljs-string">'D'</span>,<span class="hljs-number">1</span>)],
    <span class="hljs-string">'D'</span>:[(<span class="hljs-string">'B'</span>,<span class="hljs-number">5</span>),(<span class="hljs-string">'C'</span>,<span class="hljs-number">1</span>)]
}
print(prim(graph,<span class="hljs-string">'A'</span>))
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">[(<span class="hljs-string">'A'</span>,<span class="hljs-string">'B'</span>,<span class="hljs-number">1</span>), (<span class="hljs-string">'B'</span>,<span class="hljs-string">'C'</span>,<span class="hljs-number">2</span>), (<span class="hljs-string">'C'</span>,<span class="hljs-string">'D'</span>,<span class="hljs-number">1</span>)]
</code></pre>
<p>Notice how the algorithm gradually expands from node <code>A</code>, always picking the lowest-weight edge that connects a new node.</p>
<p>Let’s now look at an algorithm that can handle graphs with negative edges: Bellman-Ford.</p>
<h2 id="heading-bellman-ford-algorithm">Bellman-Ford Algorithm</h2>
<p>Bellman-Ford is a shortest path algorithm that can handle negative edge weights, unlike Dijkstra’s. It works by <strong>relaxing all edges repeatedly</strong>: if the current path to a node can be improved by going through another node, it updates the distance. After <code>V-1</code> iterations (where <code>V</code> is the number of vertices), all shortest paths are guaranteed to be found.</p>
<p>This makes it slightly slower than Dijkstra’s but more versatile. It can also detect negative weight cycles by checking for further improvements after the main loop.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">bellman_ford</span>(<span class="hljs-params">graph, start</span>):</span>
    dist = {node: float(<span class="hljs-string">'inf'</span>) <span class="hljs-keyword">for</span> node <span class="hljs-keyword">in</span> graph}
    dist[start] = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(len(graph)<span class="hljs-number">-1</span>):
        <span class="hljs-keyword">for</span> u <span class="hljs-keyword">in</span> graph:
            <span class="hljs-keyword">for</span> v,w <span class="hljs-keyword">in</span> graph[u]:
                <span class="hljs-keyword">if</span> dist[u] + w &lt; dist[v]:
                    dist[v] = dist[u] + w
    <span class="hljs-keyword">return</span> dist

graph = {
    <span class="hljs-string">'A'</span>:[(<span class="hljs-string">'B'</span>,<span class="hljs-number">4</span>),(<span class="hljs-string">'C'</span>,<span class="hljs-number">2</span>)],
    <span class="hljs-string">'B'</span>:[(<span class="hljs-string">'C'</span>,<span class="hljs-number">-1</span>),(<span class="hljs-string">'D'</span>,<span class="hljs-number">2</span>)],
    <span class="hljs-string">'C'</span>:[(<span class="hljs-string">'D'</span>,<span class="hljs-number">3</span>)],
    <span class="hljs-string">'D'</span>:[]
}
print(bellman_ford(graph,<span class="hljs-string">'A'</span>))
</code></pre>
<p>Output:</p>
<pre><code class="lang-python">{<span class="hljs-string">'A'</span>: <span class="hljs-number">0</span>, <span class="hljs-string">'B'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'C'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'D'</span>: <span class="hljs-number">5</span>}
</code></pre>
<p>Here, the shortest path to each node is found, even though there’s a negative edge (<code>B → C</code> with weight -1). If there had been a negative cycle, Bellman-Ford would detect it by noticing that distances keep improving after <code>V-1</code> iterations.</p>
<p>With the main algorithms explained, let’s move on to some practical tips for making these implementations more efficient in Python.</p>
<h2 id="heading-optimizing-graph-algorithms-in-python">Optimizing Graph Algorithms in Python</h2>
<p>When graphs get bigger, little tweaks in how you write your code can make a big difference. Here are a few simple but powerful tricks to keep things running smoothly.</p>
<p><strong>1. Use</strong> <code>deque</code> for BFS<br>If you use a regular Python list as a queue, popping items from the front takes longer the bigger the list gets. With <code>collections.deque</code>, you get instant (<code>O(1)</code>) pops from both ends. It’s basically built for this kind of job.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> deque

queue = deque([start])  <span class="hljs-comment"># fast pops and appends</span>
</code></pre>
<p><strong>2. Go Iterative with DFS</strong><br>Recursive DFS looks neat, but Python doesn’t like going too deep – you’ll hit a recursion limit if your graph is very large. The fix? Write DFS in an iterative style with a stack. Same idea, no recursion errors.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dfs_iterative</span>(<span class="hljs-params">graph, start</span>):</span>
    visited, stack = set(), [start]
    <span class="hljs-keyword">while</span> stack:
        node = stack.pop()
        <span class="hljs-keyword">if</span> node <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> visited:
            visited.add(node)
            stack.extend(graph[node])
</code></pre>
<p><strong>3. Let NetworkX Do the Heavy Lifting</strong><br>For practice and learning, writing your own graph code is great. But if you’re working on a real-world problem – say analyzing a social network or planning routes – the NetworkX library saves tons of time. It comes with optimized versions of almost every common graph algorithm plus nice visualization tools.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> networkx <span class="hljs-keyword">as</span> nx

G = nx.Graph()
G.add_edges_from([(<span class="hljs-string">'A'</span>,<span class="hljs-string">'B'</span>), (<span class="hljs-string">'A'</span>,<span class="hljs-string">'C'</span>), (<span class="hljs-string">'B'</span>,<span class="hljs-string">'D'</span>), (<span class="hljs-string">'C'</span>,<span class="hljs-string">'D'</span>)])

print(nx.shortest_path(G, source=<span class="hljs-string">'A'</span>, target=<span class="hljs-string">'D'</span>))
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">[<span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>, <span class="hljs-string">'D'</span>]
</code></pre>
<p>Instead of worrying about queues and stacks, you can let NetworkX handle the details and focus on what the results mean.</p>
<h2 id="heading-key-takeaways">Key Takeaways</h2>
<ul>
<li><p>An adjacency matrix is fast for lookups but is memory-heavy.</p>
</li>
<li><p>An adjacency list is space-efficient for sparse graphs.</p>
</li>
<li><p>NetworkX makes graph analysis much easier for real-world projects.</p>
</li>
<li><p>BFS explores layer by layer, DFS explores deeply before backtracking.</p>
</li>
<li><p>Dijkstra’s and A* handle shortest paths.</p>
</li>
<li><p>Kruskal’s and Prim’s build spanning trees.</p>
</li>
<li><p>Bellman-Ford works with negative weights.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Graphs are everywhere, from maps to social networks, and the algorithms you have seen here are the building blocks for working with them. Whether it is finding paths, building spanning trees, or handling tricky weights, these tools open up a wide range of problems you can solve.</p>
<p>Keep experimenting and try out libraries like NetworkX when you are ready to take on bigger projects.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
