Open In App

Find if there is a path of more than k weight from a source

Last Updated : 04 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an undirected graph represented by the edgeList[][], where each edgeList[i] contains three integers [u, v, w], representing an undirected edge from u to v, having distance w. You are also given a source vertex, and a positive integer k. Your task is to determine if there exist a simple path (without any cycle) starting from the source vertex and ending at any other vertex such that the total weight of the path is at least k.

Examples:

Input: source = 0, k = 58
edgeList[][] = [[0, 1, 4], [0, 7, 8], [1, 7, 11], [1, 2, 8], [2, 8, 2], [8, 6, 6], [6, 7, 1], [7, 8, 7], [2, 3, 7], [2, 5, 4], [5, 6, 2], [3, 5, 14], [3, 4, 9], [4, 5, 10]]
Output: Yes
Explanation: There exists a simple path 0 -> 7 -> 1 -> 2 -> 8 -> 6 -> 5 -> 3 -> 4, which has a total distance of 60 which is more than 58.

Input: source = 0, k = 62
edgeList[][] = [[0, 1, 4], [0, 7, 8], [1, 7, 11], [1, 2, 8], [2, 8, 2], [8, 6, 6], [6, 7, 1], [7, 8, 7], [2, 3, 7], [2, 5, 4], [5, 6, 2], [3, 5, 14], [3, 4, 9], [4, 5, 10]]
Output: No
Explanation: In the above given graph, the longest simple path has distance 61 (0 -> 7 -> 1-> 2 -> 3 -> 4 -> 5-> 6 -> 8), so output should be false for any input greater than 61.

Note : The normal greedy approach of picking the longest weight edge would not work because a shorter edge might lead to a longer path.

Using Depth First Search and Backtracking - O(V!) Time and O(V) Space

The idea is to use backtracking to explore every simple path from the source, keeping track of the remaining weight threshold at each step. We represent the graph with an adjacency list (adj) built from edgeList. Starting from src with target sum k, we recursively visit unvisited neighbors, subtracting the edge weight (w) from the remaining k. If at any point k becomes zero or negative, we’ve found a path whose total weight exceeds the original threshold. To ensure the path remains simple (no cycles), we maintain a visited map: before descending into a neighbor we mark it visited, and after returning we unmark it (backtrack).

Follow the below given steps:

  • Build the adjacency list adj[][] from edgeList, adding both directions for each undirected edge.
  • Initialize visited as an empty map and set visited[src] = 1
  • Call findPath(adj, src, k, visited)
  • In findPath:
    • If k <= 0, return true
    • For each (v, w) in adj[src]:
      • If visited[v] == 1, skip this neighbor
      • Mark visited[v] = 1
      • Recursively call findPath(adj, v, k - w, visited)
        • If it returns true, propagate true upward
      • Backtrack by setting visited[v] = 0
    • If no neighbor yields a valid path, return false
  • In pathMoreThanK, return the result of findPath to indicate whether any simple path from src has total weight more than k

Below is given the implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// recursive function to find if there
// exist simple path with weight more than k
bool findPath(unordered_map<int, vector<pair<int, int>>> &adj, 
    int src, int k, unordered_map<int, int> &visited) {

    // if k is 0 or negative, return true
    if (k <= 0) return true;

    for(auto i: adj[src]) {

        // adjacnet vertex and weight of edge
        int v = i.first, w = i.second;

        // if vertex v is visited, continue
        if (visited[v] == 1) continue;

        // else include the vertex in path
        visited[v] = 1;

        // if path greater than k is found, return true
        if(findPath(adj, v, k - w, visited))
            return true;

        // backtrack
        visited[v] = 0;
    }

    return false;
}

bool pathMoreThanK(vector<vector<int>> &edgeList, int src, int k) {

    // create an adjacency list representation of the
    // graph
    unordered_map<int, vector<pair<int, int>>> adj;
    for (const auto &edge : edgeList) {
        int u = edge[0], v = edge[1], w = edge[2];
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }

    // to mark the visited vertices
    unordered_map<int,int> visited;

    // mark source vertex visited
    visited[src] = 1;

    return findPath(adj, src, k, visited);
}

int main() {
    vector<vector<int>> edgeList = {
        {0, 1, 4}, {0, 7, 8}, {1, 7, 11}, 
        {1, 2, 8}, {2, 8, 2}, {8, 6, 6}, 
        {6, 7, 1}, {7, 8, 7}, {2, 3, 7}, 
        {2, 5, 4}, {5, 6, 2}, {3, 5, 14}, 
        {3, 4, 9}, {4, 5, 10}
    };
    int source = 0, k = 58;
    if(pathMoreThanK(edgeList, source, k))
        cout << "Yes";
    else cout << "No";
    return 0;
}
Java
import java.util.*;

class Pair {
    int first, second;
    Pair(int first, int second) {
        this.first = first;
        this.second = second;
    }
}

public class GfG {

    // recursive function to find if there
    // exist simple path with weight more than k
    public static boolean findPath(HashMap<Integer, ArrayList<Pair>> adj, 
        int src, int k, HashMap<Integer, Integer> visited) {

        // if k is 0 or negative, return true
        if (k <= 0) return true;

        for (Pair i: adj.get(src)) {

            // adjacnet vertex and weight of edge
            int v = i.first, w = i.second;

            // if vertex v is visited, continue
            if (visited.get(v) == 1) continue;

            // else include the vertex in path
            visited.put(v, 1);

            // if path greater than k is found, return true
            if (findPath(adj, v, k - w, visited))
                return true;

            // backtrack
            visited.put(v, 0);
        }

        return false;
    }

    public static boolean pathMoreThanK(
        ArrayList<ArrayList<Integer>> edgeList, int src, int k) {

        // create an adjacency list representation of the
        // graph
        HashMap<Integer, ArrayList<Pair>> adj = new HashMap<>();
        for (ArrayList<Integer> edge: edgeList) {
            int u = edge.get(0), v = edge.get(1), w = edge.get(2);
            adj.computeIfAbsent(u, x -> new ArrayList<>()).add(new Pair(v, w));
            adj.computeIfAbsent(v, x -> new ArrayList<>()).add(new Pair(u, w));
        }

        // to mark the visited vertices
        HashMap<Integer, Integer> visited = new HashMap<>();

        // initialize visited vertices to 0
        for (Integer key : adj.keySet()) {
            visited.put(key, 0);
        }

        // mark source vertex visited
        visited.put(src, 1);

        return findPath(adj, src, k, visited);
    }

    public static void main(String[] args) {
        ArrayList<ArrayList<Integer>> edgeList = 
        new ArrayList<>(Arrays.asList(
            new ArrayList<>(Arrays.asList(0, 1, 4)), 
            new ArrayList<>(Arrays.asList(0, 7, 8)), 
            new ArrayList<>(Arrays.asList(1, 7, 11)),
            new ArrayList<>(Arrays.asList(1, 2, 8)), 
            new ArrayList<>(Arrays.asList(2, 8, 2)), 
            new ArrayList<>(Arrays.asList(8, 6, 6)),
            new ArrayList<>(Arrays.asList(6, 7, 1)), 
            new ArrayList<>(Arrays.asList(7, 8, 7)), 
            new ArrayList<>(Arrays.asList(2, 3, 7)),
            new ArrayList<>(Arrays.asList(2, 5, 4)), 
            new ArrayList<>(Arrays.asList(5, 6, 2)), 
            new ArrayList<>(Arrays.asList(3, 5, 14)),
            new ArrayList<>(Arrays.asList(3, 4, 9)), 
            new ArrayList<>(Arrays.asList(4, 5, 10))
        ));
        int source = 0, k = 58;
        if (pathMoreThanK(edgeList, source, k))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}
Python
from collections import defaultdict

# recursive function to find if there
# exist simple path with weight more than k
def findPath(adj, src, k, visited):

    # if k is 0 or negative, return true
    if k <= 0:
        return True

    for i in adj[src]:

        # adjacnet vertex and weight of edge
        v, w = i

        # if vertex v is visited, continue
        if visited.get(v, 0) == 1:
            continue

        # else include the vertex in path
        visited[v] = 1

        # if path greater than k is found, return true
        if findPath(adj, v, k - w, visited):
            return True

        # backtrack
        visited[v] = 0

    return False

def pathMoreThanK(edgeList, src, k):

    # create an adjacency list representation of the
    # graph
    adj = defaultdict(list)
    for edge in edgeList:
        u, v, w = edge
        adj[u].append((v, w))
        adj[v].append((u, w))

    # to mark the visited vertices
    visited = {}

    # mark source vertex visited
    visited[src] = 1

    return findPath(adj, src, k, visited)

if __name__ == "__main__":
    edgeList = [
        [0, 1, 4], [0, 7, 8], [1, 7, 11],
        [1, 2, 8], [2, 8, 2], [8, 6, 6],
        [6, 7, 1], [7, 8, 7], [2, 3, 7],
        [2, 5, 4], [5, 6, 2], [3, 5, 14],
        [3, 4, 9], [4, 5, 10]
    ]
    source, k = 0, 58
    if pathMoreThanK(edgeList, source, k):
        print("Yes")
    else:
        print("No")
C#
using System;
using System.Collections.Generic;

public class GfG {

    // recursive function to find if there
    // exist simple path with weight more than k
    public static bool findPath(
        Dictionary<int, List<KeyValuePair<int, int>>> adj, 
        int src, int k, Dictionary<int, int> visited) {

        // if k is 0 or negative, return true
        if (k <= 0) return true;

        foreach (KeyValuePair<int, int> i in adj[src]) {

            // adjacnet vertex and weight of edge
            int v = i.Key, w = i.Value;

            // if vertex v is visited, continue
            if (visited[v] == 1) continue;

            // else include the vertex in path
            visited[v] = 1;

            // if path greater than k is found, return true
            if (findPath(adj, v, k - w, visited))
                return true;

            // backtrack
            visited[v] = 0;
        }

        return false;
    }

    public static bool pathMoreThanK(
        List<List<int>> edgeList, int src, int k) {

        // create an adjacency list representation of the
        // graph
        Dictionary<int, List<KeyValuePair<int, int>>> adj = 
        new Dictionary<int, List<KeyValuePair<int, int>>>();
        
        foreach (List<int> edge in edgeList) {
            int u = edge[0], v = edge[1], w = edge[2];
            
            if (!adj.ContainsKey(u)) adj[u] = 
            new List<KeyValuePair<int, int>>();
            adj[u].Add(new KeyValuePair<int, int>(v, w));
            
            if (!adj.ContainsKey(v)) adj[v] =
            new List<KeyValuePair<int, int>>();
            adj[v].Add(new KeyValuePair<int, int>(u, w));
        }

        // to mark the visited vertices
        Dictionary<int, int> visited = new Dictionary<int, int>();

        // initialize visited vertices to 0
        foreach (int key in adj.Keys) {
            visited[key] = 0;
        }

        // mark source vertex visited
        visited[src] = 1;

        return findPath(adj, src, k, visited);
    }

    public static void Main() {
        List<List<int>> edgeList = new List<List<int>> {
            new List<int> {0, 1, 4}, new List<int> {0, 7, 8}, 
            new List<int> {1, 7, 11}, new List<int> {1, 2, 8},
            new List<int> {2, 8, 2}, new List<int> {8, 6, 6},
            new List<int> {6, 7, 1}, new List<int> {7, 8, 7}, 
            new List<int> {2, 3, 7}, new List<int> {2, 5, 4}, 
            new List<int> {5, 6, 2}, new List<int> {3, 5, 14},
            new List<int> {3, 4, 9}, new List<int> {4, 5, 10}
        };
        int source = 0, k = 58;
        if (pathMoreThanK(edgeList, source, k))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
JavaScript
// recursive function to find if there
// exist simple path with weight more than k
function findPath(adj, src, k, visited) {

    // if k is 0 or negative, return true
    if (k <= 0) return true;

    for (let i of adj.get(src)) {

        // adjacnet vertex and weight of edge
        let v = i[0], w = i[1];

        // if vertex v is visited, continue
        if (visited.get(v) === 1) continue;

        // else include the vertex in path
        visited.set(v, 1);

        // if path greater than k is found, return true
        if (findPath(adj, v, k - w, visited))
            return true;

        // backtrack
        visited.set(v, 0);
    }

    return false;
}

function pathMoreThanK(edgeList, src, k) {

    // create an adjacency list representation of the
    // graph
    let adj = new Map();
    for (let edge of edgeList) {
        let u = edge[0], v = edge[1], w = edge[2];
        if (!adj.has(u)) adj.set(u, []);
        adj.get(u).push([v, w]);
        if (!adj.has(v)) adj.set(v, []);
        adj.get(v).push([u, w]);
    }

    // to mark the visited vertices
    let visited = new Map();

    // mark source vertex visited
    visited.set(src, 1);

    return findPath(adj, src, k, visited);
}

let edgeList = [
    [0, 1, 4], [0, 7, 8], [1, 7, 11],
    [1, 2, 8], [2, 8, 2], [8, 6, 6],
    [6, 7, 1], [7, 8, 7], [2, 3, 7],
    [2, 5, 4], [5, 6, 2], [3, 5, 14],
    [3, 4, 9], [4, 5, 10]
];
let source = 0, k = 58;
if (pathMoreThanK(edgeList, source, k))
    console.log("Yes");
else
    console.log("No");

Output
Yes

Time Complexity: O(V!), where V is the number of vertices in the graph. In the worst case—when the graph is complete—you’ll explore every simple path starting from the source and visiting all other V - 1 vertices. There are (V - 1) * (V - 2) * ... * 1 = (V - 1)! such paths.
Space Complexity: O(V)


Next Article
Article Tags :
Practice Tags :

Similar Reads