![]() |
VOOZH | about |
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: 2Input: graph = {{1,2,1}}, n = 2, k = 1
Output: 1Input: graph = {{1,2,1}}, n = 2, k = 2
Output: -1
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:
Below is the implementation of the above approach:
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).