Program to find how long it will take to reach messages in a network in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number and a list of edges. These n different nodes labeled as 0 to N. These nodes are forming a network. Each edge is in the form (a, b, t) of an undirected graph, this is representing if we try to send message from a to b or b to a, it will take t time. When a node receives a message, it immediately floods the message on to a neighboring node. If all nodes are connected, we have to find how long it will take for every node to receive a message that starts at node 0.

So, if the input is like n = 3 edges = [[0, 1, 3],[1, 2, 4],[2, 3, 2]], then the output will be 9, as the 4th node (node number 3) receives the message from 0 -> 1 -> 2 -> 3 which takes 3 + 4 + 2 = 9 amount time.

To solve this, we will follow these steps −

Define a function build_graph() . This will take edges

  • graph := an empty map
  • for each (src, dest, t) set in edges, do
    • insert (dest, t) into graph[src]
    • insert (src, t) into graph[dest]
  • return graph
  • From the main method do the following −
  • graph := build_graph(edges)
  • visited := a new set
  • heap := make a new heap with pair (0, 0)
  • while heap is not empty, do
    • (current_total_time, node) := top element of heap, and delete it from heap
    • mark node as visited
    • if number of visited nodes is same as (n + 1), then
      • return current_total_time
    • for each pair (nei, time) in graph[node], do
      • if nei not visited, then
        • insert pair (current_total_time + time, nei) into heap

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

import heapq
from collections import defaultdict
class Solution:
   def solve(self, n, edges):
      graph = self.build_graph(edges)  
      visited = set()
      heap = [(0, 0)]
      while heap:
         current_total_time, node = heapq.heappop(heap)
         visited.add(node)  
         if len(visited) == (n + 1):
            return current_total_time
         for nei, time in graph[node]:
            if nei not in visited:
               heapq.heappush(heap, (current_total_time + time, nei))
   def build_graph(self, edges):
      graph = defaultdict(set)
      for src, dest, t in edges:
         graph[src].add((dest, t))
         graph[dest].add((src, t))
      return graph
ob = Solution()
n = 3
edges = [[0, 1, 3],[1, 2, 4],[2, 3, 2]]
print(ob.solve(n, edges))

Input

3, [[0, 1, 3],[1, 2, 4],[2, 3, 2]]

Input

9
raja
Published on 12-Dec-2020 09:09:08
Advertisements