Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Shortest Path in an Undirected Graph with Unit Distance – Clear BFS Solution in Python
    Data Structures & Algorithms

    Shortest Path in an Undirected Graph with Unit Distance – Clear BFS Solution in Python

    codeanddebugBy codeanddebug13 June 2025No Comments4 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of question to Find the Shortest Path in Undirected Graph
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Find the Shortest Path in an Undirected Graph from a source to every other node when every edge costs 1. We build intuition for Breadth-First Search, walk through the code line by line, add a dry run, and finish with precise Big-O analysis.

    Here’s the [Problem Link] to begin with.

    Contents:
     [show]
    • 1. Problem statement
    • 2. Example
    • 3. Intuition & approach
      • 3.1 Why Breadth-First Search (BFS)?
      • 3.2 Algorithm steps
    • 4. Python code
    • 5. Step-by-step code explanation
    • 6. Dry run on the earlier example graph
    • 7. Complexity
    • 8. Conclusion

    1. Problem statement

    You are given an undirected graph with n vertices (0 … n-1).
    All edges have unit weight (cost = 1).

    For a given source vertex src, return an array distance where

    • distance[i] = the fewest edges needed to reach vertex i from src,
    • If a vertex is unreachable, its distance is -1.

    2. Example

    n = 6
    Edges:
    0-1, 0-2, 1-3, 2-3, 3-4
    VertexShortest path from 0Distance
    000
    10-11
    20-21
    30-1-3 or 0-2-32
    40-1-3-43
    5–-1 (not connected)

    distance = [0, 1, 1, 2, 3, -1]


    3. Intuition & approach

    3.1 Why Breadth-First Search (BFS)?

    • Every edge costs the same (1).
    • BFS explores the graph level by level:
      • Level 0 = source itself.
      • Level 1 = all vertices one edge away.
      • Level 2 = all vertices two edges away …
    • The first time BFS reaches a vertex, it has already found the shortest possible path (fewest edges).

    So BFS gives us the answer in a single scan.

    3.2 Algorithm steps

    1. Setup a queue to process vertices in order of their distance.
    2. distance[src] = 0; push (src, 0) into the queue.
    3. Pop a vertex (node, distSoFar)
      • For every neighbour adjNode
        • If the neighbour hasn’t been visited (distance == -1)
          • Set distance[adjNode] = distSoFar + 1
          • Push (adjNode, distSoFar + 1) into the queue.
    4. Repeat until the queue is empty.
    5. Return the distance array.

    Because each vertex enters the queue once, the algorithm runs in linear time.


    4. Python code

    from collections import deque
    
    
    class Solution:
        def shortestPath(self, adj, src):
            n = len(adj)                                  # number of vertices
            distance = [-1 for _ in range(n)]             # -1 = not reached yet
            queue = deque()
    
            queue.append([src, 0])                        # start from source
            distance[src] = 0
    
            while len(queue) != 0:
                node, dis_trav = queue.popleft()          # current vertex + distance
                for adjNode in adj[node]:                 # explore neighbours
                    if distance[adjNode] == -1:           # first time we see it
                        distance[adjNode] = dis_trav + 1  # shortest path fixed
                        queue.append([adjNode, dis_trav + 1])
    
            return distance

    5. Step-by-step code explanation

    1. Lines 6-8 –
      • n stores the vertex count.
      • distance array starts at -1 for every vertex.
      • queue will maintain vertices to process in FIFO order.
    2. Line 10 – Push the source (src, 0); distance to itself is 0.
    3. Main while loop (Lines 12-17)
      • popleft() fetches the closest unprocessed vertex (node) and its current shortest distance (dis_trav).
      • Loop over every neighbour adjNode:
        • Unvisited? (distance = -1)
          • Set its distance to dis_trav + 1.
          • Enqueue it with this new distance.
      • Each neighbour enters the queue once, ensuring O(V + E) time.
    4. Line 17 – When the queue empties, all reachable vertices have been assigned their minimum distances. The function returns the completed array.

    6. Dry run on the earlier example graph

    Queue state shown as [vertex, dist].

    StepQueue (before pop)distance after processing
    Init[[0,0]][0,-1,-1,-1,-1,-1]
    Pop 0neighbours 1,2 → enqueue [1,1],[2,1][0,1,1,-1,-1,-1]
    Pop 1neighbour 3 (new) → enqueue [3,2][0,1,1,2,-1,-1]
    Pop 2neighbour 3 already visitedunchanged
    Pop 3neighbour 4 → enqueue [4,3][0,1,1,2,3,-1]
    Pop 4no new neighbourunchanged
    Queue empty–Final distances

    Matches [0, 1, 1, 2, 3, -1].


    7. Complexity

    MeasureValueExplanation
    TimeO(V + E)Each vertex enqueued once; each undirected edge examined twice (once per direction)
    SpaceO(V)distance array + queue (worst-case all vertices inside)

    V = n, E = number of edges.


    8. Conclusion

    • Breadth-First Search is the go-to tool for shortest paths when all edges cost the same.
    • A single queue and a distance array are enough, no fancy data structures.
    • Because we mark a vertex the first time we see it, its distance is already minimal.
    • The solution is linear, easy to code, and scales to very large sparse graphs.
    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    BFS Graph Medium
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleCheck if array is sorted | Explained using Python Code
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Check if array is sorted | Explained using Python Code

    13 June 2025
    Data Structures & Algorithms

    Find the second largest and second smallest element in an Array | Explained

    13 June 2025
    Data Structures & Algorithms

    Quick Sort Algorithm in Python | Explained

    13 June 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (49)
      • Beginner (24)
      • Expert (9)
      • Intermediate (16)
    • Uncategorised (1)
    Recent Posts

    Shortest Path in an Undirected Graph with Unit Distance – Clear BFS Solution in Python

    13 June 2025

    Check if array is sorted | Explained using Python Code

    13 June 2025

    Find the second largest and second smallest element in an Array | Explained

    13 June 2025

    Quick Sort Algorithm in Python | Explained

    13 June 2025

    Merge Sort Algorithm in Python | Explained

    13 June 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

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