VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-bridges-required-to-be-crossed-to-reach-nth-city/

⇱ Minimum bridges required to be crossed to reach N<sup>th</sup> city - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum bridges required to be crossed to reach Nth city

Last Updated : 3 Oct, 2025

Given an integer N denoting the number of connected cities ( numbered from 1 to N ) and a 2D array arr[][] consisting of pairs connected to each other by bidirectional bridges. The task is to find the minimum the number of bridges required to be crossed to reach the city N from the city 1.

Examples:

Input: N = 3, M = 2, arr[][] = {{1, 2}, {2, 3}}

👁 Image

Output: 2
Explanation: 
To reach Node 2 from Node 1, 1 bridge is required to be crossed. 
To reach Node 3 from Node 2, 1 bridge is required to be crossed.
Hence, 2 bridges are required to be connected.

Input: N = 4, M = 3, arr[][] = {{1, 2}, {2, 3}, {2, 4}}
Output: 2

Approach: Follow the steps below to solve the problem:

  • Initialize an adjacency list to build and store the Graph nodes.
  • Initialize an array, say vis[] of size N to mark the visited nodes and another array, say dist[] of size N, to store the minimum distance from city 1.
  • Perform BFS and using the concept of Single Source Shortest Path to traverse the graph and store the minimum number of bridges required to be crossed to reach every city from city 1.
  • Print the value of dist[N] as the minimum distance to reach city N from city 1.

Below is the implementation of the above approach:

 
 


Output: 
2

 


 

Time Complexity: O(N)
Auxiliary Space: O(N)


 

Comment