21. Shortest Path in Undirected Graph

The problem can be found at the following link: Question Link

Note: Sorry for uploading late; my exam is going on.

Problem Description

You are given an undirected graph with n nodes and m edges, all edges having a unit weight. Your task is to find the shortest path from a given source vertex src to all other vertices. If any vertex is unreachable from the source, return -1 for that vertex.

Example:

Input:

n = 9, m = 10
edges = [[0,1],[0,3],[3,4],[4,5],[5,6],[1,2],[2,6],[6,7],[7,8],[6,8]]
src = 0

Output:

0 1 2 1 2 3 3 4 4

Input:

n = 4, m = 2
edges = [[1,3],[3,0]]
src = 3

Output:

1 1 -1 0

Constraints:

  • (1 \leq n, m \leq 10^4)

  • (0 \leq edges[i][j] \leq n-1)

My Approach

  1. Graph Representation:

    • First, represent the graph using an adjacency list, where each vertex points to a list of its neighboring vertices.

  2. Breadth-First Search (BFS):

    • Use BFS to explore the shortest path in an unweighted graph. Initialize a distance array dist with INT_MAX (or float('inf') in Python) to signify that the nodes are initially unreachable.

    • Start BFS from the source node src, setting its distance to 0.

    • For each node, update the distance of its neighboring nodes if the current path offers a shorter distance.

    • If a node remains with INT_MAX distance after BFS, set its distance to -1 to indicate that it is unreachable from the source.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(N + E), where N is the number of nodes and E is the number of edges, since we are performing a BFS traversal across the graph.

  • Expected Auxiliary Space Complexity: O(N), as we store the adjacency list and the distance array, both of size N.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated