VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-of-edges-between-two-vertices-of-a-graph/

⇱ Minimum number of edges between two vertices - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number of edges between two vertices

Last Updated : 10 Jan, 2026

Given a graph with V vertices and E edges and two vertices u, v present in the graph. Find the minimum number of edges in the path between these two vertices. If the path doesn't exist, return -1.

Examples:

Input: u = 2, v = 5

πŸ‘ frame_3149

Output: 2
Explanation: The path between vertex 2 and vertex 5: 2 -> 3 -> 5, has 2 edges.


Input: u = 1, v = 5

πŸ‘ 420046859

Output: -1
Explanation: There is no path between the two vertices.

[Naive Approach] Using DFS - O(N!) time and O(V) space

The idea is to perform a DFS traversal starting from vertex u. From each vertex, we recursively explore all possible paths to reach the destination vertex v, keeping track of the number of edges traversed. Whenever we reaches to v, we update the minimum count among all discovered paths. If no path is found after exploring all possibilities, we return -1.


Output
2

[Expected Approach] Using BFS - O(V+E) time and O(V) space

The idea is to perform a BFS starting from the source vertex while tracking the level (or distance) of each vertex. The first time the destination vertex is reached, the current level represents the minimum number of edges between the two nodes.

This works because BFS explores the graph level by level β€” it visits all nodes at distance 1 before distance 2, and so on. Hence, when we first encounter the destination, it’s guaranteed to be through the shortest possible path.


Output
2
Comment
Article Tags:
Article Tags: