Find if there is a path of more thank length from a source
Pattern: BFS and DFS
Search every simple path from the source with backtracking: walk to an unused neighbour, subtract the edge's weight from what is still needed, and undo the step afterwards. As soon as the needed amount reaches 0 or less, the answer is yes. This is exponential, which is expected: the problem is NP-hard.
The problem
Given an undirected weighted graph and k, return whether some simple path (no repeated vertex) starting at vertex 0
has total weight at least k. Edges are [u, v, weight].
Think first
- Why not use a shortest-path style algorithm?
- What must a path never do?
- When can you stop early?
Hints
Brute force, and why it fails
List every simple path and its weight: the same exponential work without early stopping.
The key insight
Backtracking with an 'on the path' mark explores each simple path once and stops at the first one long enough.
Dry run
The 9-vertex example from source 0 with k = 58. Try 0 → 7 → 1 → 2 → 8 → 6 → 5 → 4 → 3 and similar paths.
The plan
explore(u, need): if need <= 0: true
for (v, w) in adj[u]: if v not on path: mark v; if explore(v, need - w): true; unmark v
Complexity
- Time
O(V!) worst case- Space
O(V)
Every simple path may be tried; the path itself is at most V long.
Edge cases
- k = 0: true straight away.
- A single vertex.
- Weights that sum to exactly k: true.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public boolean pathMoreThanK(int n, int[][] edges, int k) {
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i < n; 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[] onPath = new boolean[n];
onPath[0] = true;
return explore(0, k, adj, onPath);
}
private boolean explore(int u, int need, List<List<int[]>> adj, boolean[] onPath) { // a simple path from u worth need?
if (need <= 0) return true;
for (int[] e : adj.get(u)) {
int v = e[0];
if (onPath[v]) continue; // a simple path never repeats a vertex
onPath[v] = true;
if (explore(v, need - e[1], adj, onPath)) return true;
onPath[v] = false; // backtrack
}
return false;
}
}C++
class Solution {
public:
bool pathMoreThanK(int n, vector<vector<int>>& edges, int k) {
vector<vector<pair<int, int>>> adj(n);
for (const vector<int>& e : edges) { 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[0] = true;
return explore(0, k, adj, onPath);
}
bool explore(int u, int need, vector<vector<pair<int, int>>>& adj, vector<bool>& onPath) { // a simple path worth need?
if (need <= 0) return true;
for (const pair<int, int>& e : adj[u]) {
int v = e.first;
if (onPath[v]) continue; // a simple path never repeats a vertex
onPath[v] = true;
if (explore(v, need - e.second, adj, onPath)) return true;
onPath[v] = false; // backtrack
}
return false;
}
};Python
class Solution:
def pathMoreThanK(self, n: int, edges: list[list[int]], k: int) -> bool:
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
on_path = [False] * n
on_path[0] = True
def explore(u, need) -> bool: # a simple path from u worth need?
if need <= 0:
return True
for v, w in adj[u]:
if not on_path[v]: # a simple path never repeats a vertex
on_path[v] = True
if explore(v, need - w):
return True
on_path[v] = False # backtrack
return False
return explore(0, k)Common mistakes
- Marking vertices visited for good instead of undoing on the way back.
- Using
>when the problem allows equality.