VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimizing-infection-time-in-a-directed-graph/

⇱ Minimizing Infection Time in a Directed Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimizing Infection Time in a Directed Graph

Last Updated : 23 Jul, 2025

Given a directed graph of N nodes [1, N] represented by a 2D array graph[][], and an integer K which is the initially infected node. The graph[i] = (ui, vi, wi) represents the infection spreads from ui to vi in wi unit of time. The task is to find the minimum time required for the entire graph to be infected starting from node K. If it is not possible to infect all the nodes, return -1.

Examples:

Input: graph = {{2, 1, 1}, {2, 3, 1}, {3, 4, 1}}, n = 4, k = 2
Output: 2

Input: graph = {{1,2,1}}, n = 2, k = 1
Output: 1

Input: graph = {{1,2,1}}, n = 2, k = 2
Output: -1

Minimizing Infection Time in a Directed Graph using Dijkstra's Algorithm:

Use Dijkstra's algorithm to find the shortest time for infecting all nodes in a directed graph from a given starting node 'k'. The maximum distance (here, it is time) in the dist[] array indicates the minimum time for complete infection. If some nodes are unreachable, returns -1.

Step-by-step approach:

  • Create an adjacency list to represent the directed graph, where each node is associated with its neighbors and the time it takes to propagate the infection to them.
  • Initialize a priority queue (min-heap) to keep track of nodes with the shortest distance from the source node. Start from the source node k with a distance of 0.
  • Use Dijkstra's algorithm to explore nodes and update their distances. If a shorter path to a node is found, update its distance and push it into the priority queue.
  • Keep track of the maximum distance found in the dist[] array, which represents the time to infect all nodes.
  • Check, If the maximum distance is still at its initial value (INT_MAX), it means not all nodes are reachable, so return -1. Otherwise, return the maximum distance as the minimum time to infect the complete graph.

Below is the implementation of the above approach:


Output
Minimum time to infect all nodes: 2

Time Complexity: O((V + E) * log(V)), where V is the number of vertices (nodes) and E is the number of edges in the graph.
Auxiliary Space: O(V) for the distance array and O(V) for the priority queue, resulting in a total space complexity of O(V).

Comment