You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
Input: times = [[1,2,1]], n = 2, k = 1
Output: 1
Input: times = [[1,2,1]], n = 2, k = 2
Output: -1
Dijkstra’s algorithm is a classic approach to find the shortest paths from a single source node to all other nodes in a graph with non-negative edge weights. By using a priority queue, we can efficiently choose the next node to process based on the smallest known distance.
Integer.MAX_VALUE) values to represent the shortest time (distance) from source K to each node. Set the distance to the source node K as 0.K.O(E log V), where E is the number of edges and V is the number of vertices, due to the heap operations.O(V + E), for storing the graph and the distance table.The Bellman-Ford algorithm is another method to compute the shortest paths from a single source node to all other nodes in a graph, and it can handle negative weights. It repetitively relaxes all edges, updating the shortest paths.
Integer.MAX_VALUE), except for the source node K which is set to 0.u to v with weight w, if the current distance to u plus w is less than the distance to v, update the distance to v.-1.O(V * E), as each of the V vertices requires E edge relaxations.O(V), as we only maintain a simple distance array.