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

Finding a path longer than a given length in a graph is a classic graph traversal problem. We need to determine if there exists a simple path (without cycles) from a source vertex to any other vertex with total edge weights exceeding a threshold k.

0 1 2 3 4 5 6 7 8 5 12 9 Example: Path 0?7?1?2?8?6?5?3?4 = 68 > k(64)

Algorithm Overview

The solution uses backtracking with DFS to explore all possible paths from the source vertex. We maintain a visited array to prevent cycles and recursively check if any path exceeds the required length k.

Implementation

class Graph:
    def __init__(self, nodes):
        self.nodes = nodes
        self.adj = [[] for i in range(nodes)]
    
    def insert_edge(self, u, v, w):
        self.adj[u].append([v, w])
        self.adj[v].append([u, w])
    
    def solve(self, source, k, path):
        # If remaining distance is 0 or negative, we found a valid path
        if k <= 0:
            return True
        
        # Explore all adjacent vertices
        for neighbor in self.adj[source]:
            v, w = neighbor[0], neighbor[1]
            
            # Skip if vertex is already visited (avoid cycles)
            if path[v]:
                continue
            
            # If this edge alone satisfies the condition
            if w >= k:
                return True
            
            # Mark vertex as visited and explore further
            path[v] = True
            if self.solve(v, k - w, path):
                return True
            path[v] = False  # Backtrack
        
        return False
    
    def is_there_any_path(self, source, k):
        path = [False] * self.nodes
        path[source] = True  # Mark source as visited
        return self.solve(source, k, path)

# Create graph with 9 nodes
nodes = 9
g = Graph(nodes)

# Add edges with weights
g.insert_edge(0, 1, 5)
g.insert_edge(0, 7, 9)
g.insert_edge(1, 2, 9)
g.insert_edge(1, 7, 12)
g.insert_edge(2, 3, 8)
g.insert_edge(2, 8, 3)
g.insert_edge(2, 5, 5)
g.insert_edge(3, 4, 10)
g.insert_edge(3, 5, 15)
g.insert_edge(4, 5, 11)
g.insert_edge(5, 6, 3)
g.insert_edge(6, 7, 2)
g.insert_edge(6, 8, 7)
g.insert_edge(7, 8, 8)

source = 0
k = 64
result = g.is_there_any_path(source, k)
print(f"Path longer than {k} from vertex {source}: {result}")
Path longer than 64 from vertex 0: True

How It Works

The algorithm follows these key steps:

  • Base Case: If remaining distance k ? 0, we've found a valid path
  • Edge Exploration: For each unvisited neighbor, check if the edge weight alone satisfies the condition
  • Recursive Search: Mark vertex as visited, reduce k by edge weight, and recursively search
  • Backtracking: Unmark vertex to allow other paths to use it

Time Complexity

The time complexity is O(V!) in the worst case, where V is the number of vertices, as we might explore all possible permutations of vertices in a complete graph.

Conclusion

This backtracking approach efficiently finds paths longer than k by exploring all possible simple paths from a source vertex. The algorithm uses DFS with visited tracking to avoid cycles and returns true as soon as any valid path is found.

Updated on: 2026-03-25T09:40:51+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements