Problem solution · Python

Modify Graph Edge Weights

Modify Graph Edge Weights: a Python solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Heap or priority queue
Source
walkccc LeetCode Solutions
Length
55 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Modify Graph Edge Weights, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 55 lines of Python from the credited upstream file 2699.py.
  • The implementation visibly relies on sequence storage, work queue.
  • No explicit loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeModify Graph Edge Weights · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def modifiedGraphEdges(self, n: int, edges: list[list[int]], source: int, destination: int, target: int) -> list[list[int]]:    MAX = 2_000_000_000    graph = [[] for _ in range(n)]     for u, v, w in edges:      if w == -1:        continue      graph[u].append((v, w))      graph[v].append((u, w))     distToDestination = self._dijkstra(graph, source, destination)    if distToDestination < target:      return []    if distToDestination == target:      # Change the weights of negative edges to an impossible value.      for edge in edges:        if edge[2] == -1:          edge[2] = MAX      return edges     for i, (u, v, w) in enumerate(edges):      if w != -1:        continue      edges[i][2] = 1      graph[u].append((v, 1))      graph[v].append((u, 1))      distToDestination = self._dijkstra(graph, source, destination)      if distToDestination <= target:        edges[i][2] += target - distToDestination        # Change the weights of negative edges to an impossible value.        for j in range(i + 1, len(edges)):          if edges[j][2] == -1:            edges[j][2] = MAX        return edges     return []   def _dijkstra(self, graph: list[list[int]], src: int, dst: int) -> int:    dist = [math.inf] * len(graph)     dist[src] = 0    minHeap = [(dist[src], src)]  # (d, u)     while minHeap:      d, u = heapq.heappop(minHeap)      if d > dist[u]:        continue      for v, w in graph[u]:        if d + w < dist[v]:          dist[v] = d + w          heapq.heappush(minHeap, (dist[v], v))     return dist[dst] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗