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

Pattern: Rat in a maze

medium

Walk outwards from the source along edges, keeping track of how much length is still needed and which vertices are on the path. Stop with yes as soon as the remaining length is 0 or less; undo and try other edges otherwise.

The problem

Given an undirected graph with positive edge lengths, a source vertex and a number k, return whether there is a simple path (no vertex repeated) starting at the source whose total length is at least k. For example, in the 9-vertex graph of the GeeksforGeeks article, k = 58 gives true and k = 62 gives false.

The link above is a GeeksforGeeks article. The function name pathMoreThanK(n, edges, src, k) and the input form (each edge as [u, v, length]) are this guide's own. Graphs are explained on the Structures page.

Think first

  • Why must vertices not repeat?
  • What should the recursion carry so you know when to stop?
  • Is there a fast exact method in general?

Hints

    Brute force, and why it fails

    List every simple path from the source and check its length: that is what backtracking does, with an early stop. No polynomial method is known, since this generalises the longest-path problem.

    The key insight

    Stopping at the first path that is long enough often ends the search early. In the worst case, every simple path must be tried, so this only suits small graphs.

    Dry run

    00 
    11 
    left5

    Two vertices joined by an edge of length 5. The source is 0 and k = 5.

    Step 1 of 4

    The plan

    mark src
    function extend(u, left):
        if left <= 0: return true
        for (v, w) in adj[u]:
            if v is marked: continue
            mark v
            if extend(v, left - w): return true
            unmark v
        return false
    return extend(src, k)
    

    Complexity

    Time
    O(n!) worst
    Space
    O(n)

    A simple path can visit the vertices in many orders. The marks and recursion are O(n).

    Edge cases

    • k ≤ 0: true, the empty path is enough.
    • An isolated source with k > 0: false.
    • Cycles: the marks stop a path from going round them.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public boolean pathMoreThanK(int n, int[][] edges, int src, int k) {
            List<List<int[]>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
            for (int[] e : edges) {                         // undirected, weighted
                adj.get(e[0]).add(new int[]{e[1], e[2]});
                adj.get(e[1]).add(new int[]{e[0], e[2]});
            }
            boolean[] onPath = new boolean[n];
            onPath[src] = true;
            return extend(adj, src, k, onPath);
        }
    
        private boolean extend(List<List<int[]>> adj, int u, int left, boolean[] onPath) {
            if (left <= 0) return true;                     // the path so far is already long enough
            for (int[] e : adj.get(u)) {
                int v = e[0], w = e[1];
                if (onPath[v]) continue;                    // a simple path: no vertex twice
                onPath[v] = true;
                if (extend(adj, v, left - w, onPath)) return true;
                onPath[v] = false;                          // undo and try another edge
            }
            return false;
        }
    }

    C++

    class Solution {
    public:
        bool pathMoreThanK(int n, vector<vector<int>>& edges, int src, int k) {
            vector<vector<pair<int, int>>> adj(n);
            for (const vector<int>& e : edges) {            // undirected, weighted
                adj[e[0]].push_back(make_pair(e[1], e[2]));
                adj[e[1]].push_back(make_pair(e[0], e[2]));
            }
            vector<bool> onPath(n, false);
            onPath[src] = true;
            return extend(adj, src, k, onPath);
        }
    
        bool extend(vector<vector<pair<int, int>>>& adj, int u, int left, vector<bool>& onPath) {
            if (left <= 0) return true;                     // the path so far is already long enough
            for (const pair<int, int>& e : adj[u]) {
                int v = e.first, w = e.second;
                if (onPath[v]) continue;                    // a simple path: no vertex twice
                onPath[v] = true;
                if (extend(adj, v, left - w, onPath)) return true;
                onPath[v] = false;                          // undo and try another edge
            }
            return false;
        }
    };

    Python

    class Solution:
        def pathMoreThanK(self, n: int, edges: list[list[int]], src: int, k: int) -> bool:
            adj = [[] for _ in range(n)]
            for u, v, w in edges:                   # undirected, weighted
                adj[u].append((v, w))
                adj[v].append((u, w))
            on_path = [False] * n
            on_path[src] = True
    
            def extend(u: int, left: int) -> bool:
                if left <= 0:
                    return True                     # the path so far is already long enough
                for v, w in adj[u]:
                    if on_path[v]:
                        continue                    # a simple path: no vertex twice
                    on_path[v] = True
                    if extend(v, left - w):
                        return True
                    on_path[v] = False              # undo and try another edge
                return False
    
            return extend(src, k)

    Common mistakes

    • Marking vertices as visited forever, which blocks other paths.
    • Adding each edge in one direction only.
    • Using shortest-path algorithms, which answer a different question.

    Similar problems