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.

C++
//Driver Code Starts
#include <iostream>
#include <vector>
using namespace std;

//Driver Code Ends

int dfs(int curr, int dest, vector<vector<int>>& adj, 
        vector<bool>& visited) {
    if (curr == dest) return 0;
    
    visited[curr] = true;
    int minEdges = (int)1e9;
    for (int next : adj[curr]) {
        if (!visited[next]) {
            // moving to next nodes adds 
            // 1 edge to the path
            minEdges = min(minEdges, 1 + dfs(next, dest, adj, visited));
        }
    }
    visited[curr] = false;
    return minEdges;
}

// function for finding minimum no. of 
// edges between u and v
int minEdges(vector<vector<int>>& adj, int u, int v) {
    int V = adj.size();
    vector<bool> visited(V, false);
    int minEdgesCount = dfs(u, v, adj, visited);
    return minEdgesCount == (int)1e9 ? -1 : minEdgesCount;

//Driver Code Starts
}

void addEdge(vector<vector<int>>& adj, int u, int v) {
    adj[u].push_back(v);
    adj[v].push_back(u);
}


int main() {
    int V = 6;
    vector<vector<int>> adj(V);
    
    // creating adjacency list
    addEdge(adj, 0, 1);
    addEdge(adj, 1, 2);
    addEdge(adj, 2, 3);
    addEdge(adj, 3, 4);
    addEdge(adj, 4, 5);
    addEdge(adj, 3, 5);

    int u = 2, v = 5;
    int minEdgesCount = minEdges(adj, u, v);

    cout << minEdgesCount << endl;
    return 0;
}

//Driver Code Ends
Java
//Driver Code Starts
import java.util.ArrayList;

class GfG {

//Driver Code Ends

    // Method for finding minimum no. 
    // of edges between u and v
    static int minEdges(ArrayList<ArrayList<Integer>> adj, int u, int v) {
        int V = adj.size();
        boolean[] visited = new boolean[V];
        int minEdges = dfs(u, v, adj, visited);
        return minEdges == (int) 1e9 ? -1 : minEdges;
    }

    static int dfs(int curr, int dest, ArrayList<ArrayList<Integer>> adj, boolean[] visited) {
        if (curr == dest)
            return 0;

        visited[curr] = true;
        int minEdges = (int) 1e9;

        for (int next : adj.get(curr)) {
            if (!visited[next]) {
                // moving to next nodes adds 1 edge to the path
                minEdges = Math.min(minEdges, 1 + dfs(next, dest, adj, visited));
            }
        }
        visited[curr] = false;
        return minEdges;
    }

//Driver Code Starts

    static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) {
        adj.get(u).add(v);
        adj.get(v).add(u);
    }
    
    public static void main(String[] args) {
        int V = 6;
        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
        
        // creating adjacency list
        for (int i = 0; i < V; i++)
            adj.add(new ArrayList<>());

        addEdge(adj, 0, 1);
        addEdge(adj, 1, 2);
        addEdge(adj, 2, 3);
        addEdge(adj, 3, 4);
        addEdge(adj, 4, 5);
        addEdge(adj, 3, 5);

        int u = 2, v = 5;
        int minEdges = minEdges(adj, u, v);

        System.out.println(minEdges);
    }
}
//Driver Code Ends
Python
def dfs(curr, dest, adj, visited):
    if curr == dest:
        return 0

    visited[curr] = True
    minEdges = 10**9

    for nxt in adj[curr]:
        if not visited[nxt]:
            # moving to next node adds 
            # 1 edge to the path
            minEdges = min(minEdges, 1 + dfs(nxt, dest, adj, visited))
            
    visited[curr] = false        
    return minEdges

# Method for finding minimum no. 
# of edges between u and v
def minEdges(adj, u, v):
    V = len(adj)
    visited = [False] * V
    res = dfs(u, v, adj, visited)

    return -1 if res == 10**9 else res
#Driver Code Starts


def addEdge(adj, u, v):
    adj[u].append(v)
    adj[v].append(u)
  
  
if __name__ == "__main__":
    V = 6
    adj = []
    
    # creating adjacency list
    for i in range(V):
        adj.append([])
        
    addEdge(adj, 0, 1)
    addEdge(adj, 1, 2)
    addEdge(adj, 2, 3)
    addEdge(adj, 3, 4)
    addEdge(adj, 4, 5)
    addEdge(adj, 3, 5)
    
    u, v = 2, 5
    print(minEdges(adj, u, v))

#Driver Code Ends
C#
//Driver Code Starts
using System;
using System.Collections.Generic;

class GfG {
    
//Driver Code Ends

    static int dfs(int curr, int dest, List<List<int>> adj, bool[] visited) {
        if (curr == dest) return 0;

        visited[curr] = true;
        int minEdges = (int)1e9;
        foreach (int next in adj[curr]) {
            if (!visited[next]) {
                // moving to next nodes adds 
                // 1 edge to the path
                minEdges = Math.Min(minEdges, 1 + dfs(next, dest, adj, visited));
            }
        }
        visited[curr] = false;
        return minEdges;
    }

    // Method for finding minimum 
    // no. of edgeS between u and v
    static int minEdges(List<List<int>> adj, int u, int v) {
        int V = adj.Count;
        bool[] visited = new bool[V];
        int minEdgesCount = dfs(u, v, adj, visited);
        return minEdgesCount == (int)1e9 ? -1 : minEdgesCount;

//Driver Code Starts
    }

     static void addEdge(List<List<int>> adj, int u, int v) {
        adj[u].Add(v);
        adj[v].Add(u);
    }
    
    static void Main() {
        int V = 6;
        List<List<int>> adj = new List<List<int>>();
        
        // creating adjacency list
        for (int i = 0; i < V; i++)
            adj.Add(new List<int>());
            
        addEdge(adj, 0, 1);
        addEdge(adj, 1, 2);
        addEdge(adj, 2, 3);
        addEdge(adj, 3, 4);
        addEdge(adj, 4, 5);
        addEdge(adj, 3, 5);

        int u = 2, v = 5;
        int minEdgesCount = minEdges(adj, u, v);

        Console.WriteLine(minEdgesCount);
    }
}

//Driver Code Ends
JavaScript
// Method for finding minimum 
// no. of edges between u and v
function dfs(curr, dest, adj, visited) {
    if (curr === dest) return 0;

    visited[curr] = true;
    let minEdges = 1e9;
    for (let next of adj[curr]) {
        if (!visited[next]) {
            // moving to next nodes adds 
            // 1 edge to the path
            minEdges = Math.min(minEdges, 1 + dfs(next, dest, adj, visited));
        }
    }
    visited[curr] = false;
    return minEdges;
}

function minEdges(adj, u, v) {
    const V = adj.length;
    const visited = new Array(V).fill(false);
    const minEdgesCount = dfs(u, v, adj, visited);
    return minEdgesCount === 1e9 ? -1 : minEdgesCount;

}
//Driver Code Starts

function addEdge(adj, u, v) {
    adj[u].push(v);
    adj[v].push(u);
}

// Driver code

let V = 6;
let adj = [];

// creating adjacency list
for (let i = 0; i < V; i++)
    adj.push([]);

addEdge(adj, 0, 1);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
addEdge(adj, 4, 5);
addEdge(adj, 3, 5);

const u = 2, v = 5;
const minEdgesCount = minEdges(adj, u, v);

console.log(minEdgesCount);
//Driver Code Ends

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.

C++
//Driver Code Starts
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

//Driver Code Ends

int bfs(int src, int dest, vector<vector<int>>& adj, 
        vector<bool>& visited) {
    queue<pair<int, int>> q;
    q.push({src, 0});

    while (!q.empty()) {
        auto [curr, edges] = q.front();
        q.pop();

        if (visited[curr]) continue;

        // return the first time we reach the destination
        if (curr == dest) return edges;

        visited[curr] = true;
        for (int next : adj[curr]) {
            q.push({next, edges + 1});
        }
    }

    // no path found
    return -1;
}

// function for finding minimum no. of 
// edges between u and v
int minEdges(vector<vector<int>>& adj, int u, int v) {
    int V = adj.size();
    vector<bool> visited(V, false);
    int minEdgesCount = bfs(u, v, adj, visited);
    return minEdgesCount == (int)1e9 ? -1 : minEdgesCount;
}

//Driver Code Starts

void addEdge(vector<vector<int>>& adj, int u, int v) {
    adj[u].push_back(v);
    adj[v].push_back(u);
}

int main() {
    int V = 6;
    vector<vector<int>> adj(V);
    
    // creating adjacency list
    addEdge(adj, 0, 1);
    addEdge(adj, 1, 2);
    addEdge(adj, 2, 3);
    addEdge(adj, 3, 4);
    addEdge(adj, 4, 5);
    addEdge(adj, 3, 5);

    int u = 2, v = 5;
    int minEdgesCount = minEdges(adj, u, v);

    cout << minEdgesCount << endl;
    return 0;
}

//Driver Code Ends
Java
//Driver Code Starts
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
import java.util.ArrayList;

class Test{
//Driver Code Ends

    // Method for finding minimum no. of edges
    // using BFS
    static int minEdges(ArrayList<ArrayList<Integer>> adj, int u, int v) {
        int V = adj.size();
        boolean[] visited = new boolean[V];
        int minEdges = bfs(u, v, adj, visited);
        return minEdges == (int)1e9 ? -1 : minEdges;
    }
    static int bfs(int src, int dest, 
    ArrayList<ArrayList<Integer>> adj, boolean[] visited) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{src, 0});
    
        while (!queue.isEmpty()) {
            int[] top = queue.poll();
            int curr = top[0];
            int edges = top[1];
    
            if (visited[curr]) continue;
            
            // return the first time we
            // reach the destination
            if (curr == dest) return edges;
    
            visited[curr] = true;
            for (int next : adj.get(curr)) {
                queue.offer(new int[]{next, edges + 1});
            }
        }
        
        // no path found
        return -1;
    }

//Driver Code Starts

    static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) {
        adj.get(u).add(v);
        adj.get(v).add(u);
    }
    
    public static void main(String[] args) {
        int V = 6;
        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
        
        // creating adjacency list
        for (int i = 0; i < V; i++)
            adj.add(new ArrayList<>());

        addEdge(adj, 0, 1);
        addEdge(adj, 1, 2);
        addEdge(adj, 2, 3);
        addEdge(adj, 3, 4);
        addEdge(adj, 4, 5);
        addEdge(adj, 3, 5);
        
        int u = 2; int v = 5;
        int minEdges = minEdges(adj, u, v);

        System.out.println(minEdges);
    }
}
//Driver Code Ends
Python
#Driver Code Starts
from collections import deque

#Driver Code Ends

def bfs(src, dest, adj, visited):
    queue = deque()
    queue.append((src, 0))

    while queue:
        curr, edges = queue.popleft()

        if visited[curr]:
            continue

        # return the first time we reach the destination
        if curr == dest:
            return edges

        visited[curr] = True
        for next_node in adj[curr]:
            queue.append((next_node, edges + 1))

    # no path found
    return -1

# Method for finding minimum no. 
# of edges between u and v
def minEdges(adj, u, v):
    V = len(adj)
    visited = [False] * V
    res = bfs(u, v, adj, visited)
    return -1 if res == 10**9 else res

#Driver Code Starts


def addEdge(adj, u, v):
    adj[u].append(v)
    adj[v].append(u)
  
  
if __name__ == "__main__":
    V = 6
    adj = []
    
    # creating adjacency list
    for i in range(V):
        adj.append([])
        
    addEdge(adj, 0, 1)
    addEdge(adj, 1, 2)
    addEdge(adj, 2, 3)
    addEdge(adj, 3, 4)
    addEdge(adj, 4, 5)
    addEdge(adj, 3, 5)
    
    u, v = 2, 5
    print(minEdges(adj, u, v))
#Driver Code Ends
C#
//Driver Code Starts
using System;
using System.Collections.Generic;

class GFG {
//Driver Code Ends

    // Method for finding minimum number of edges
    // between u and v
    static int MinEdges(List<List<int>> adj, int u, int v) {
        int V = adj.Count;
        bool[] visited = new bool[V];
        int minEdges = bfs(u, v, adj, visited);
        return minEdges == int.MaxValue ? -1 : minEdges;
    }

    static int bfs(int src, int dest, List<List<int>> adj, bool[] visited) {
        Queue<int[]> queue = new Queue<int[]>();
        queue.Enqueue(new int[]{src, 0});

        while (queue.Count > 0) {
            int[] top = queue.Dequeue();
            int curr = top[0];
            int edges = top[1];

            if (visited[curr]) continue;

            // return the first time we reach the destination
            if (curr == dest) return edges;

            visited[curr] = true;
            foreach (int next in adj[curr]) {
                queue.Enqueue(new int[]{next, edges + 1});
            }
        }

        // no path found
        return -1;
    }

//Driver Code Starts

     static void addEdge(List<List<int>> adj, int u, int v) {
        adj[u].Add(v);
        adj[v].Add(u);
    }
    
    static void Main() {
        int V = 6;
        List<List<int>> adj = new List<List<int>>();
        
        // creating adjacency list
        for (int i = 0; i < V; i++)
            adj.Add(new List<int>());
            
        addEdge(adj, 0, 1);
        addEdge(adj, 1, 2);
        addEdge(adj, 2, 3);
        addEdge(adj, 3, 4);
        addEdge(adj, 4, 5);
        addEdge(adj, 3, 5);

        int u = 2, v = 5;
        int minEdges = MinEdges(adj, u, v);
        Console.WriteLine(minEdges);
    }
}
//Driver Code Ends
JavaScript
// Method for finding minimum 
// no. of edges between u and v
function bfs(src, dest, adj, visited) {
    // Using a standard array as queue
    let queue = [];
    queue.push([src, 0]);

    while (queue.length > 0) {
        let [curr, edges] = queue.shift();

        if (visited[curr]) continue;

        // return the first time we reach the destination
        if (curr === dest) return edges;

        visited[curr] = true;
        for (let next of adj[curr]) {
            queue.push([next, edges + 1]);
        }
    }

    // no path found
    return -1;
}

function minEdges(adj, u, v) {
    const V = adj.length;
    const visited = new Array(V).fill(false);
    const minEdgesCount = bfs(u, v, adj, visited);
    return minEdgesCount === 1e9 ? -1 : minEdgesCount;
}


//Driver Code Starts
function addEdge(adj, u, v) {
    adj[u].push(v);
    adj[v].push(u);
}

// Driver code

let V = 6;
let adj = [];

// creating adjacency list
for (let i = 0; i < V; i++)
    adj.push([]);

addEdge(adj, 0, 1);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
addEdge(adj, 4, 5);
addEdge(adj, 3, 5);

const u = 2, v = 5;
const minEdgesCount = minEdges(adj, u, v);

console.log(minEdgesCount);
//Driver Code Ends

Output
2
Comment