times
, where each element times[i]
is of the form [u, v, w]
, representing a directed edge from node u
to node v
with travel time w
.N
, representing the total number of nodes.K
, representing the starting node.K
. If it is impossible for all nodes to receive the signal, return -1
.This problem can be solved using graph algorithms like Dijkstra’s algorithm, which is well-suited for finding the shortest path in a graph with non-negative weights.
Data Representation: Use an adjacency list to store the graph representation.
Algorithm Choice: Utilize Dijkstra’s algorithm to find the shortest time to each node starting from node K
.
Priority Queue: Use a priority queue (min-heap) to always extend the shortest known path.
K
.-1
.where V
is the number of nodes and E
is the number of edges.
Let’s go ahead and implement this:
import heapq
from collections import defaultdict
def networkDelayTime(times, N, K):
# Create a graph in the form of an adjacency list
graph = defaultdict(list)
for u, v, w in times:
graph[u].append((w, v))
# Priority queue to hold (travel_time, node)
min_heap = [(0, K)]
# Dictionary to store the shortest travel time to each node
shortest_time = {}
while min_heap:
travel_time, node = heapq.heappop(min_heap)
if node in shortest_time:
continue
shortest_time[node] = travel_time
for time, neighbor in graph[node]:
if neighbor not in shortest_time:
heapq.heappush(min_heap, (travel_time + time, neighbor))
# Check if we visited all nodes
if len(shortest_time) == N:
return max(shortest_time.values())
else:
return -1
# Example usage
times = [[2,1,1],[2,3,1],[3,4,1]]
N = 4
K = 2
print(networkDelayTime(times, N, K)) # Output: 2
K
and a travel time of 0
.N
nodes. If true, we return the maximum travel time; otherwise, -1
.This approach ensures that we efficiently find the shortest path to each node in the network using Dijkstra’s algorithm with a min-heap.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?