711976. Shortest Path in Undirected Graph

Medium

Shortest Path in Undirected Graph Having Unit Distance

Summary

The problem is to find the shortest path between two nodes in an undirected graph where all edges have a unit distance. This problem involves basic concepts of graph theory, such as graph traversal and finding the shortest path. The key concept involved is Breadth-First Search (BFS).

Detailed Explanation

To solve this problem, we can use Breadth-First Search (BFS) algorithm. BFS traverses the graph level by level, starting from a given source node.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty queue and add the source node to it.
  2. Mark the source node as visited.
  3. Dequeue a node from the queue and mark its adjacent unvisited nodes as visited and enqueue them.
  4. Repeat step 3 until the destination node is dequeued or the queue becomes empty.
  5. When the destination node is dequeued, follow the path from the source node to the destination node by backtracking from the destination node to the source node.

Here's a diagram illustrating this process:

         +--------+
         |        |
         |  Source  |
         |        |
         +--------+

         +--------+
         |        |
         |    Node 1|
         |        |
         +--------+

         +--------+
         |        |
         |   Node 2  |
         |        |
         +--------+

...and so on

Time complexity analysis: The time complexity of BFS is O(V+E), where V is the number of vertices and E is the number of edges. This is because we visit each vertex once and traverse each edge once.

Space complexity analysis: The space complexity of BFS is O(V), as in the worst-case scenario, we need to store all vertices in the queue.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

class Node {
    int val;
    boolean visited;

    public Node(int val) {
        this.val = val;
        this.visited = false;
    }
}

public class Main {
    static void shortestPath(Node[] nodes, int source, int dest) {
        Node[] nodesCopy = Arrays.copyOf(nodes, nodes.length);
        nodesCopy[source].visited = true;

        Queue<Integer> queue = new LinkedList<>();
        queue.add(source);

        while (!queue.isEmpty()) {
            int node = queue.poll();
            if (node == dest) {
                // Follow the path from source to destination
                List<Integer> path = new ArrayList<>();
                while (node != source) {
                    path.add(node);
                    node = nodesCopy[node].val;
                }
                path.add(source);
                Collections.reverse(path);
                System.out.println("Shortest Path: " + path);
                return;
            }

            for (int neighbor : getNeighbors(nodes, node)) {
                if (!nodes[neighbor].visited) {
                    nodes[neighbor].visited = true;
                    queue.add(neighbor);
                }
            }
        }
    }

    static int[] getNeighbors(Node[] nodes, int node) {
        // Get neighbors of the given node
        // For simplicity, assume all edges have a unit distance
        return new int[] {node - 1, node + 1};
    }

    public static void main(String[] args) {
        Node[] nodes = new Node[5];
        for (int i = 0; i < 5; i++) {
            nodes[i] = new Node(i);
        }
        shortestPath(nodes, 0, 4); // Example usage
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.