AlgoMaster Logo

Network Delay Time

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Dijkstra's Algorithm

Intuition:

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.

Steps:

  1. Graph Representation: We first represent the graph using an adjacency list where each node points to its neighbors along with the time taken to reach them.
  2. Priority Queue (Min-Heap): Initialize a min-heap that will store elements as pairs of (time, node). The heap will prioritize nodes with smaller times.
  3. Distance Table: Create a distance table initialized with infinity (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.
  4. Processing Nodes:
    • While the priority queue is not empty, remove the node with the smallest time.
    • For each neighbor of the current node, calculate the new time to reach that neighbor.
    • If this new time is smaller than the previously recorded time in the distance table, update the table and add the neighbor to the priority queue.
  5. Finding the Result: The result is the maximum value from the distance table. If there's any node that remains at infinity, it means it's unreachable from the source K.

Code:

2. Bellman-Ford Algorithm

Intuition:

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.

Steps:

  1. Initialize Distance Array: Create a distance array with all nodes initially set to infinity (Integer.MAX_VALUE), except for the source node K which is set to 0.
  2. Relax Edges N-1 Times:
    • For each edge from 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.
  3. Checking for Negative Cycles: (Not required for this problem since edge weights are non-negative)
    • Run the relaxation step once more to check for improvements, which indicate negative cycles. For this problem, it can be skipped as all weights are positive.
  4. Determine the Result: Find the maximum time in the distance array. If all nodes are reachable, return this maximum time; otherwise, return -1.

Code: