Program to Find Out the Minimum Cost Possible from Weighted Graph in Python

Finding the minimum cost path in a weighted graph where cost is defined as the product of path length and maximum edge weight requires a specialized approach. This problem combines shortest path algorithms with weight constraints to optimize the overall cost function.

Problem Understanding

Given an undirected weighted graph represented as edges [u, v, w], we need to find the minimum cost path from node 0 to node n-1. The cost formula is:

Cost = Number of edges × Maximum weight in the path

Algorithm Approach

The solution uses a binary search-like approach on edge weights combined with BFS:

  1. Build the graph representation from edges
  2. Try different maximum weight thresholds starting from the highest
  3. For each threshold, use BFS to find the shortest path using only edges ? threshold
  4. Calculate cost and keep track of the minimum

Example

Let's trace through the given example ?

from collections import defaultdict, deque

class Solution:
    def solve(self, edges):
        graph = defaultdict(list)
        weights = {}
        max_weight = 0
        N = 0
        
        # Build graph representation
        for u, v, w in edges:
            graph[u].append(v)
            graph[v].append(u)
            weights[u, v] = w
            weights[v, u] = w
            N = max(N, u + 1, v + 1)
            max_weight = max(max_weight, w)
        
        def bfs(root, weight_cap):
            target = N - 1
            Q = deque([(root, 0, 0)])  # (node, distance, current_max_weight)
            visited = [False] * N
            visited[0] = True
            
            while Q:
                v, d, current_weight = Q.pop()
                if v == N - 1:
                    return d, current_weight
                
                for w in graph[v]:
                    if visited[w]:
                        continue
                    new_weight = weights[v, w]
                    if new_weight <= weight_cap:
                        visited[w] = True
                        Q.appendleft((w, d + 1, max(current_weight, new_weight)))
            
            return -1, -1
        
        result = float("inf")
        
        # Try different weight thresholds
        while max_weight >= 0:
            d, weight = bfs(0, max_weight)
            if d >= 0:
                result = min(result, d * weight)
                max_weight = weight - 1
            else:
                break
        
        return result if result < float("inf") else -1

# Test the solution
ob = Solution()
edges = [
    [0, 2, 100],
    [1, 2, 200], 
    [1, 3, 100],
    [2, 3, 300]
]
print(ob.solve(edges))
600

How It Works

For the given example:

  1. Graph structure: Nodes 0-3 connected as specified
  2. Path analysis: From node 0 to node 3, possible paths are:
    • 0 ? 2 ? 3: 2 edges, max weight 300, cost = 2 × 300 = 600
    • 0 ? 2 ? 1 ? 3: 3 edges, max weight 200, cost = 3 × 200 = 600
  3. Optimal solution: Both paths give the same minimum cost of 600

Key Points

  • The algorithm tries different weight thresholds to balance path length vs. maximum weight
  • BFS ensures shortest path for a given weight constraint
  • Time complexity: O(E × W × (V + E)) where W is the range of weights
  • Returns -1 if no path exists between source and destination

Conclusion

This solution efficiently finds the minimum cost path by iteratively constraining edge weights and using BFS to find shortest paths. The approach balances the trade-off between path length and maximum edge weight to minimize the overall cost.

Updated on: 2026-03-25T13:57:33+05:30

840 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements