Floyd warshall algorithm

Graphs Shortest Path Algorithms Hard
  • This problem is a direct application of the Floyd-Warshall algorithm, a core concept utilized in the field of routing and navigation
  • Software applications like Google Maps, GPS systems, and various shipping and logistics platforms often use variations of this algorithm to calculate and suggest the shortest path from one location to another
  • This not only saves time but is also essential for enhancing the route efficiency of autonomous vehicles, drones and robotic systems

Given a graph of V vertices numbered from 0 to V-1. Find the shortest distances between every pair of vertices in a given edge-weighted directed graph. The graph is represented as an adjacency matrix of size n x n. Matrix[i][j] denotes the weight of the edge from i to j. If matrix[i][j]=-1, it means there is no edge from i to j.

Examples:

Input: matrix = [[0, 2, -1, -1],[1, 0, 3, -1],[-1, -1, 0, 1],[3, 5, 4, 0]]

Output: [[0, 2, 5, 6], [1, 0, 3, 4], [4, 6, 0, 1], [3, 5, 4, 0]] 

Explanation: matrix[0][0] is storing the distance from vertex 0 to vertex 0, the distance from vertex 0 to vertex 1 is 2 and so on.

Input: matrix = [[0,25],[-1,0]]

Output: [[0, 25],[-1, 0]]

Explanation: The matrix already contains the shortest distance.

Input: matrix = [[0,1,43],[1,0,6],[-1,-1,0]]

Constraints

  • 1 <= n <= 100
  • -1 <= matrix[ i ][ j ] <= 1000

Hints

  • " Initialize a dist[][] matrix: If matrix[i][j] != -1, set dist[i][j] = matrix[i][j]. If i == j, set dist[i][i] = 0. If matrix[i][j] == -1, set dist[i][j] = ∞ (indicating no direct path)."
  • "Run three nested loops (O(V³)): Use each vertex k as an intermediate node and check if going through k provides a shorter path and Detect negative weight cycles."

Company Tags

Boston Consulting Group Robinhood Ubisoft AMD Zynga Airbnb Oracle Shopify NVIDIA Johnson & Johnson PwC Bloomberg Bungie Stripe Dropbox Unity Technologies Qualcomm Zoho JPMorgan Chase Byju's Riot Games Databricks Square Wayfair Zomato Google Microsoft Amazon Meta Apple Netflix Adobe