Shortest Path in Undirected Graph with Unit Distance - Visualization

Problem Statement

Given an Undirected Graph with unit weights (i.e., every edge has weight 1), the task is to compute the shortest path from a given source node (assumed to be 0) to all other nodes in the graph.

If a node is unreachable from the source, return -1 for that node.

Examples

Graph Start Node Shortest Distances Description
{ 0: [1, 2], 1: [0, 3], 2: [0], 3: [1] } 0 [0, 1, 1, 2] Node 0 connects directly to 1 and 2; node 3 is two steps away.
{ 0: [1], 1: [0], 2: [] } 0 [0, 1, -1] Node 2 is disconnected from the rest of the graph.
{} 0 [] Empty graph with no nodes.
{ 0: [] } 0 [0] Single node with no edges; self-distance is 0.

Solution

Understanding the Problem

We are given an undirected graph where all edges have a unit distance (i.e., weight = 1). Our goal is to find the shortest path from the source node (usually node 0) to all other nodes in the graph. This is a classic case for using Breadth-First Search (BFS), because BFS is guaranteed to find the shortest path in graphs with unweighted or unit-weighted edges.

To achieve this, we will construct the graph using an adjacency list and traverse it level by level using BFS, keeping track of the shortest distance to each node.

Step-by-Step Solution with Example

Step 1: Represent the graph

We use an adjacency list to store the graph. Each node maps to a list of its neighbors. This representation is efficient and simple to use for BFS.

Step 2: Initialize the distance array

Create a distance[] array with size equal to the number of nodes. Initially, set all values to -1 to indicate that they are not reachable. Set distance[0] to 0 since the distance from the source to itself is always zero.

Step 3: Perform BFS

Use a queue to start from the source node (node 0). At each step:

  • Dequeue the current node
  • For each of its neighbors, if that neighbor's distance is still -1, set it to distance[current] + 1 and enqueue it

This ensures that each node is visited in the shortest possible way.

Step 4: Example Walkthrough

Let's consider the following simple graph:


Input:
n = 5
edges = [
  [0, 1],
  [0, 2],
  [1, 3],
  [2, 4]
]

Graph visualization:

  • Node 0 is connected to 1 and 2
  • Node 1 connects further to 3
  • Node 2 connects to 4

Using BFS starting from node 0:

  • Distance to 0: 0
  • Distance to 1: 1 (via 0 → 1)
  • Distance to 2: 1 (via 0 → 2)
  • Distance to 3: 2 (via 0 → 1 → 3)
  • Distance to 4: 2 (via 0 → 2 → 4)
Final distance array: [0, 1, 1, 2, 2]

Edge Cases

  • Disconnected nodes: If a node is unreachable from the source, its distance will remain -1
  • Single-node graph: The distance array will be [0] since it's the only node
  • No edges: All nodes except the source will remain unreachable
  • Cycles: BFS still guarantees shortest paths because it visits each node only once using the smallest possible number of edges

Finally

Using BFS for shortest paths in an undirected unit-weight graph is both efficient and intuitive. The key idea is to explore all neighbors at each level before going deeper, which ensures minimum edge traversal. This method easily adapts to real-world problems like social network connections, network packet routing, and more.

Algorithm Steps

  1. Initialize an array distance with -1 for all nodes.
  2. Set distance[0] = 0 as the source is node 0.
  3. Initialize a queue and enqueue node 0.
  4. While the queue is not empty:
    1. Dequeue the front node as current.
    2. For each neighbor of current:
      1. If distance[neighbor] == -1, set distance[neighbor] = distance[current] + 1 and enqueue the neighbor.
  5. Return the distance array.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>

#define MAX 1000

int queue[MAX], front = 0, rear = 0;

void enqueue(int val) {
    queue[rear++] = val;
}

int dequeue() {
    return queue[front++];
}

int isEmpty() {
    return front == rear;
}

int main() {
    int n = 4;
    int edges[][2] = {{0,1},{0,2},{1,3}};
    int m = sizeof(edges)/sizeof(edges[0]);

    int graph[MAX][MAX] = {0};
    int degree[MAX] = {0};
    int distance[MAX];

    for (int i = 0; i < m; i++) {
        int u = edges[i][0], v = edges[i][1];
        graph[u][degree[u]++] = v;
        graph[v][degree[v]++] = u;
    }

    for (int i = 0; i < n; i++) distance[i] = -1;
    distance[0] = 0;
    enqueue(0);

    while (!isEmpty()) {
        int current = dequeue();
        for (int i = 0; i < degree[current]; i++) {
            int neighbor = graph[current][i];
            if (distance[neighbor] == -1) {
                distance[neighbor] = distance[current] + 1;
                enqueue(neighbor);
            }
        }
    }

    for (int i = 0; i < n; i++) {
        printf("%d ", distance[i]);
    }
    printf("\n");
    return 0;
}

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...