Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Designing For TV: Principles, Patterns And Practical Guidance (Part 2)

      September 5, 2025

      Neo4j introduces new graph architecture that allows operational and analytics workloads to be run together

      September 5, 2025

      Beyond the benchmarks: Understanding the coding personalities of different LLMs

      September 5, 2025

      Top 10 Use Cases of Vibe Coding in Large-Scale Node.js Applications

      September 3, 2025

      Building smarter interactions with MCP elicitation: From clunky tool calls to seamless user experiences

      September 4, 2025

      From Zero to MCP: Simplifying AI Integrations with xmcp

      September 4, 2025

      Distribution Release: Linux Mint 22.2

      September 4, 2025

      Coded Smorgasbord: Basically, a Smorgasbord

      September 4, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Drupal 11’s AI Features: What They Actually Mean for Your Team

      September 5, 2025
      Recent

      Drupal 11’s AI Features: What They Actually Mean for Your Team

      September 5, 2025

      Why Data Governance Matters More Than Ever in 2025?

      September 5, 2025

      Perficient Included in the IDC Market Glance for Digital Business Professional Services, 3Q25

      September 5, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      How DevOps Teams Are Redefining Reliability with NixOS and OSTree-Powered Linux

      September 5, 2025
      Recent

      How DevOps Teams Are Redefining Reliability with NixOS and OSTree-Powered Linux

      September 5, 2025

      Distribution Release: Linux Mint 22.2

      September 4, 2025

      ‘Cronos: The New Dawn’ was by far my favorite experience at Gamescom 2025 — Bloober might have cooked an Xbox / PC horror masterpiece

      September 4, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Graph Algorithms in Python: BFS, DFS, and Beyond

    Graph Algorithms in Python: BFS, DFS, and Beyond

    September 4, 2025

    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 structures in computer science. They help model relationships efficiently, from social networks to transportation systems.

    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.

    Table of Contents:

    1. Understanding Graphs in Python

    2. Ways to Represent Graphs in Python

    3. Breadth-First Search (BFS)

    4. Depth-First Search (DFS)

    5. Dijkstra’s Algorithm

    6. A* Search

    7. Kruskal’s Algorithm

    8. Prim’s Algorithm

    9. Bellman-Ford Algorithm

    10. Optimizing Graph Algorithms in Python

    11. Key Takeaways

    Understanding Graphs in Python

    A graph consists of nodes (vertices) and edges (relationships).

    For examples, in a social network, people are nodes and friendships are edges. Or in a roadmap, cities are nodes and roads are edges.

    There are a few different types of graphs:

    • Directed: edges have direction (one-way streets, task scheduling).

    • Undirected: edges go both ways (mutual friendships).

    • Weighted: edges have values (distances, costs).

    • Unweighted: edges are equal (basic subway routes).

    Now that you know what graphs are, let’s look at the different ways they can be represented in Python.

    Ways to Represent Graphs in Python

    Before diving into traversal and pathfinding, it’s important to know how graphs can be represented. Different problems call for different representations.

    Adjacency Matrix

    An adjacency matrix is a 2D array where each cell (i, j) shows whether there is an edge from node i to node j.

    • In an unweighted graph, 0 means no edge, and 1 means an edge exists.

    • In a weighted graph, the cell holds the edge weight.

    This makes it very quick to check if two nodes are directly connected (constant-time lookup), but it uses more memory for large graphs.

    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>]
    ]
    

    Here, the matrix shows a fully connected graph of 3 nodes. For example, graph[0][1] = 1 means there is an edge from node 0 to node 1.

    Adjacency List

    An adjacency list represents each node along with the list of nodes it connects to.

    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.

    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>]
    }
    

    Here, node A connects to B and C, and so on. Checking connections takes a little longer than with a matrix, but for large, sparse graphs, it’s the better option.

    Using NetworkX

    When working on real-world applications, writing your own adjacency lists and matrices can get tedious. That’s where NetworkX comes in, a Python library that simplifies graph creation and analysis.

    With just a few lines of code, you can build graphs, visualize them, and run advanced algorithms without reinventing the wheel.

    <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()
    

    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.

    Now that we’ve seen different ways to represent graphs, let’s move on to traversal methods, starting with Breadth-First Search (BFS).

    Breadth-First Search (BFS)

    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.

    BFS is particularly useful for:

    • Finding the shortest path in unweighted graphs

    • Detecting connected components

    • Crawling web pages

    Here’s an example:

    <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>)
    

    Here’s what’s going on in this code:

    • graph is a dict where each node maps to a list of neighbors.

    • deque is used as a FIFO queue so we visit nodes level-by-level.

    • visited keeps track of nodes we’ve already processed so we don’t loop forever on cycles.

    • In the loop, we pop a node, print it, then for each unvisited neighbor, we mark it visited and enqueue it.

    And here’s the output:

    A B C D E F
    

    Now that we have seen how BFS works, let’s turn to its counterpart: Depth-First Search (DFS).

    Depth-First Search (DFS)

    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.

    We can implement DFS in two ways:

    • Recursive DFS, which uses the function call stack

    • Iterative DFS, which uses an explicit stack

    DFS is especially useful for:

    • Cycle detection

    • Maze solving and puzzles

    • Topological sorting

    Here’s an example of recursive DFS:

    <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>)
    
    • visited is a set that tracks nodes already processed so you don’t loop forever on cycles.

    • On each call, if node hasn’t been seen, it’s printed, marked visited, then the function recurses into each neighbor.

    Traversal order:

    A B D E F C
    

    Explanation: DFS visits B after A, goes deeper into D, then backtracks to explore E and F, and finally visits C.

    And here’s an example of iterative DFS:

    <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>)
    
    • visited tracks nodes you’ve already processed so you don’t loop on cycles.

    • stack is LIFO (last in, first out) – you pop() the top node, process it, then push its neighbors.

    • reversed(graph[node]) pushes neighbors in reverse so they’re visited in the original left-to-right order (mimicking the usual recursive DFS).

    Here’s the output:

    A B D E F C
    

    With BFS and DFS explained, we can now move on to algorithms that solve more complex problems, starting with Dijkstra’s shortest path algorithm.

    Dijkstra’s Algorithm

    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.

    <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 < 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>))
    

    Here’s what’s going on in this code:

    • graph is an adjacency list: each node maps to a list of (neighbor, weight) pairs.

    • shortest_path stores the current best-known distance to each node (∞ initially, 0 for start).

    • heap (priority queue) holds frontier nodes as (cost, node), always popping the smallest cost first.

    • For each popped node, it relaxes its edges: for each (neighbor, weight), compute new_cost. If new_cost beats shortest_path[neighbor], update it and push the neighbor with that cost.

    And here’s the output:

    {<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>}
    

    Moving on, let’s look at an extension of this algorithm: A Search.*

    A* Search

    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.

    <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 > 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 < 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>))
    

    This one’s a little more complex, so here’s what’s going on:

    • graph: adjacency list – each node maps to [(neighbor, weight), ...].

    • heuristic(node, goal): returns an estimate h(node) (lower is better). It’s passed goal but in this demo uses a fixed dict.

    • g_costs: best known cost from start to each node (∞ initially, 0 for start).

    • heap: min-heap of (priority, node) where priority = g + h.

    • came_from: backpointers to reconstruct the path once we pop the goal.

    Then in the main loop:

    • We pop the node with smallest priority.

    • If it’s the goal, we backtrack via came_from to build the path and return it with g_costs[goal].

    • Otherwise, we relax the edges: for each (neighbor, weight), compute new_cost = g_costs[node] + weight. If new_cost improves g_costs[neighbor], update it, set came_from[neighbor] = node, and push (new_cost + heuristic(neighbor, goal), neighbor).

    Output:

    ([<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>)
    

    Next up, let’s move from shortest paths to spanning trees. This is where Kruskal’s algorithm comes in.

    Kruskal’s Algorithm

    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.

    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.

    <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] > 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))
    

    Output:

    [(<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>)]
    

    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.

    Prim’s Algorithm

    Prim’s algorithm also finds an MST, but it grows the tree step by step. It starts with one node and repeatedly adds the smallest edge that connects the current tree to a new node. Think of it as expanding a connected “island” until all nodes are included.

    This implementation uses a priority queue (heapq) to always select the smallest available edge efficiently.

    <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>))
    

    Output:

    [(<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>)]
    

    Notice how the algorithm gradually expands from node A, always picking the lowest-weight edge that connects a new node.

    Let’s now look at an algorithm that can handle graphs with negative edges: Bellman-Ford.

    Bellman-Ford Algorithm

    Bellman-Ford is a shortest path algorithm that can handle negative edge weights, unlike Dijkstra’s. It works by relaxing all edges repeatedly: if the current path to a node can be improved by going through another node, it updates the distance. After V-1 iterations (where V is the number of vertices), all shortest paths are guaranteed to be found.

    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.

    <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 < 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>))
    

    Output:

    {<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>}
    

    Here, the shortest path to each node is found, even though there’s a negative edge (B → C with weight -1). If there had been a negative cycle, Bellman-Ford would detect it by noticing that distances keep improving after V-1 iterations.

    With the main algorithms explained, let’s move on to some practical tips for making these implementations more efficient in Python.

    Optimizing Graph Algorithms in Python

    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.

    1. Use deque for BFS
    If you use a regular Python list as a queue, popping items from the front takes longer the bigger the list gets. With collections.deque, you get instant (O(1)) pops from both ends. It’s basically built for this kind of job.

    <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>
    

    2. Go Iterative with DFS
    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.

    <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])
    

    3. Let NetworkX Do the Heavy Lifting
    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.

    <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>))
    

    Output:

    [<span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>, <span class="hljs-string">'D'</span>]
    

    Instead of worrying about queues and stacks, you can let NetworkX handle the details and focus on what the results mean.

    Key Takeaways

    • An adjacency matrix is fast for lookups but is memory-heavy.

    • An adjacency list is space-efficient for sparse graphs.

    • NetworkX makes graph analysis much easier for real-world projects.

    • BFS explores layer by layer, DFS explores deeply before backtracking.

    • Dijkstra’s and A* handle shortest paths.

    • Kruskal’s and Prim’s build spanning trees.

    • Bellman-Ford works with negative weights.

    Conclusion

    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.

    Keep experimenting and try out libraries like NetworkX when you are ready to take on bigger projects.

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleHow the Node.js Event Loop Works
    Next Article Best AI Overviews Tracking Tools: Dominate Google’s AI-Driven Search Results

    Related Posts

    Development

    How to Fine-Tune Large Language Models

    September 5, 2025
    Artificial Intelligence

    Scaling Up Reinforcement Learning for Traffic Smoothing: A 100-AV Highway Deployment

    September 5, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-6694 – LabRedesCefetRJ WeGIA Cross-Site Scripting Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    How Deutsche Bahn redefines forecasting using Chronos models – Now available on Amazon Bedrock Marketplace

    Machine Learning

    CVE-2025-33043 – APTIOV BIOS Improper Input Validation Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-48955 – “Para Exposes Access and Secret Keys in Logs”

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    What’s the Real Cost of Building an AI Solution in 2025? A Comprehensive Guide💰

    May 15, 2025

    Post Content Source: Read More 

    Microsoft 50th Anniversary Copilot Event interrupted by protester

    April 4, 2025

    CVE-2025-3712 – “LCD KVM over IP Switch CL5708IM Heap-based Buffer Overflow Denial-of-Service Vulnerability”

    May 9, 2025

    This big cult hit classic arcade-style fighter has finally arrived for Xbox — here’s what you need to know

    May 30, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.