Distance Greater Than or Equal to K from a Source

Last Updated : 10 Jul, 2026

Given an undirected weighted graph with V vertices numbered from 0 to V - 1 and an integer k, find if there exists a simple path starting from vertex 0 whose total path weight is greater than or equal to k. A simple path is a path in which no vertex is visited more than once.

Examples:

Input: V = 5, edges[][] = [[0, 1, 4], [0, 2, 8], [1, 4, 6], [2, 3, 2], [4, 3, 10]], k = 8
Output: true
Explanation: One possible simple path is 0 -> 1 -> 4. The total path weight is 4 + 6 = 10, which is greater than or equal to k = 8. Hence, a valid path exists and the answer is true.

123456

Input: V = 4 , edges[][] = [[0, 1, 5], [1, 2, 1], [2, 3, 1]], k = 8
Output: false
Explanation: There exists no path which has a distance of 8.

Try It Yourself
redirect icon

[Expected Approach] Using DFS and Backtracking - O(V!) Time and O(V) Space

Since a simple path cannot contain repeated vertices, we can explore all possible paths using DFS while marking visited vertices. As we traverse an edge, we reduce the remaining weight required by its weight. If the remaining weight becomes non-positive, a valid path has been found. After exploring a path, we backtrack by unmarking the current vertex so that it can be used in other potential paths.

Step By Step Implementation:

  • Build an adjacency list from the given edge list.
  • Create a visited array to avoid revisiting vertices and maintain a simple path.
  • Start DFS from vertex 0 with the required path length k.
  • For every unvisited neighbor, check if its edge weight is enough to satisfy the remaining length.
  • Otherwise, continue DFS with the remaining weight reduced by the edge weight.
  • If any DFS call succeeds, return true.
  • Backtrack by unmarking the current vertex after exploring all paths through it.
  • Return false if no valid path is found.
C++
#include <iostream>
#include <vector>
using namespace std;

bool dfs(int u, int k, vector<vector<pair<int, int>>>& adj,
         vector<bool>& vis) {

    // Required path length has been achieved.
    if (k <= 0)
        return true;

    vis[u] = true;

    for (auto& [v, wt] : adj[u]) {

        // Skip already visited vertices.
        if (vis[v])
            continue;

        // Taking this edge alone satisfies the requirement.
        if (wt >= k)
            return true;

        // Explore further with reduced remaining length.
        if (dfs(v, k - wt, adj, vis))
            return true;
    }

    // Backtrack for other possible paths.
    vis[u] = false;

    return false;
}

bool pathMoreThanK(int V, vector<vector<int>>& edges, int k) {

    vector<vector<pair<int, int>>> adj(V);

    for (auto& e : edges) {
        adj[e[0]].push_back({e[1], e[2]});
        adj[e[1]].push_back({e[0], e[2]});
    }

    vector<bool> vis(V, false);

    return dfs(0, k, adj, vis);
}

int main() {
    int V = 5;
    vector<vector<int>> edges = {
        {0, 1, 4},
        {0, 2, 8},
        {1, 4, 6},
        {2, 3, 2},
        {4, 3, 10}
    };
    int k = 8;

    cout << (pathMoreThanK(V, edges, k) ? "true" : "false");

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

class GFG {

    static boolean dfs(int u, int k,
                       List<List<int[]>> adj,
                       boolean[] vis) {

        // Required path length has been achieved.
        if (k <= 0)
            return true;

        vis[u] = true;

        for (int[] edge : adj.get(u)) {
            int v = edge[0];
            int wt = edge[1];

            // Skip already visited vertices.
            if (vis[v])
                continue;

            // Taking this edge alone satisfies the requirement.
            if (wt >= k)
                return true;

            // Explore further with reduced remaining length.
            if (dfs(v, k - wt, adj, vis))
                return true;
        }

        // Backtrack for other possible paths.
        vis[u] = false;

        return false;
    }

    static boolean pathMoreThanK(int V, int[][] edges, int k) {

        List<List<int[]>> adj = new ArrayList<>();

        for (int i = 0; i < V; i++)
            adj.add(new ArrayList<>());

        for (int[] e : edges) {
            adj.get(e[0]).add(new int[] {e[1], e[2]});
            adj.get(e[1]).add(new int[] {e[0], e[2]});
        }

        boolean[] vis = new boolean[V];

        return dfs(0, k, adj, vis);
    }

    public static void main(String[] args) {
        int V = 5;

        int[][] edges = {
            {0, 1, 4},
            {0, 2, 8},
            {1, 4, 6},
            {2, 3, 2},
            {4, 3, 10}
        };

        int k = 8;

        System.out.println(pathMoreThanK(V, edges, k));
    }
}
Python
def dfs(u, k, adj, vis):

    # Required path length has been achieved.
    if k <= 0:
        return True

    vis[u] = True

    for v, wt in adj[u]:

        # Skip already visited vertices.
        if vis[v]:
            continue

        # Taking this edge alone satisfies the requirement.
        if wt >= k:
            return True

        # Explore further with reduced remaining length.
        if dfs(v, k - wt, adj, vis):
            return True

    # Backtrack for other possible paths.
    vis[u] = False

    return False


def pathMoreThanK(V, edges, k):
    adj = [[] for _ in range(V)]

    for u, v, w in edges:
        adj[u].append((v, w))
        adj[v].append((u, w))

    vis = [False] * V

    return dfs(0, k, adj, vis)


V = 5

edges = [
    [0, 1, 4],
    [0, 2, 8],
    [1, 4, 6],
    [2, 3, 2],
    [4, 3, 10]
]

k = 8

print(str(pathMoreThanK(V, edges, k)).lower())
C#
using System;
using System.Collections.Generic;

class GFG
{
    static bool DFS(int u, int k,
                    List<List<(int, int)>> adj,
                    bool[] vis)
    {
        // Required path length has been achieved.
        if (k <= 0)
            return true;

        vis[u] = true;

        foreach (var edge in adj[u])
        {
            int v = edge.Item1;
            int wt = edge.Item2;

            // Skip already visited vertices.
            if (vis[v])
                continue;

            // Taking this edge alone satisfies the requirement.
            if (wt >= k)
                return true;

            // Explore further with reduced remaining length.
            if (DFS(v, k - wt, adj, vis))
                return true;
        }

        // Backtrack for other possible paths.
        vis[u] = false;

        return false;
    }

    static bool PathMoreThanK(int V, int[][] edges, int k)
    {
        List<List<(int, int)>> adj = new();

        for (int i = 0; i < V; i++)
            adj.Add(new List<(int, int)>());

        foreach (var e in edges)
        {
            adj[e[0]].Add((e[1], e[2]));
            adj[e[1]].Add((e[0], e[2]));
        }

        bool[] vis = new bool[V];

        return DFS(0, k, adj, vis);
    }

    static void Main()
    {
        int V = 5;

        int[][] edges =
        {
            new int[] {0, 1, 4},
            new int[] {0, 2, 8},
            new int[] {1, 4, 6},
            new int[] {2, 3, 2},
            new int[] {4, 3, 10}
        };

        int k = 8;

        Console.WriteLine(
            PathMoreThanK(V, edges, k).ToString().ToLower()
        );
    }
}
JavaScript
function dfs(u, k, adj, vis) {

    // Required path length has been achieved.
    if (k <= 0)
        return true;

    vis[u] = true;

    for (const [v, wt] of adj[u]) {

        // Skip already visited vertices.
        if (vis[v])
            continue;

        // Taking this edge alone satisfies the requirement.
        if (wt >= k)
            return true;

        // Explore further with reduced remaining length.
        if (dfs(v, k - wt, adj, vis))
            return true;
    }

    // Backtrack for other possible paths.
    vis[u] = false;

    return false;
}

function pathMoreThanK(V, edges, k) {
    const adj = Array.from({ length: V }, () => []);

    for (const [u, v, w] of edges) {
        adj[u].push([v, w]);
        adj[v].push([u, w]);
    }

    const vis = new Array(V).fill(false);

    return dfs(0, k, adj, vis);
}

// Driver Code
const V = 5;

const edges = [
    [0, 1, 4],
    [0, 2, 8],
    [1, 4, 6],
    [2, 3, 2],
    [4, 3, 10]
];

const k = 8;

console.log(pathMoreThanK(V, edges, k));

Output
true
Comment