Similar Problems

Similar Problems not available

Minimum Score Of A Path Between Two Cities - Leetcode Solution

Companies:

LeetCode:  Minimum Score Of A Path Between Two Cities Leetcode Solution

Difficulty: Medium

Topics: breadth-first-search union-find depth-first-search graph  

The Minimum Score of a Path Between Two Cities problem on LeetCode is a dynamic programming problem where we have to find the minimum score of a path between two cities in a graph. The cities are represented by the nodes of the graph and the cost of traveling between the cities is represented by the edges of the graph. The score of a path is the maximum cost of the edges on the path.

Algorithm:

  1. Start by creating a 2D array D where D[i][j] represents the minimum score of the path between city i and city j. Initialize all elements with Infinity.

  2. Fill in the diagonal elements of the array with 0 as the minimum score between a city and itself is 0.

  3. For each edge in the graph, we update the minimum score of the path between the two cities connected by the edge. If the new score is less than the current score, we update the D array with the new score.

  4. For each city i, we iterate through all the other cities j and k. We update the D[i][j] with the minimum of D[i][j] and max(D[i][k], D[k][j]) where k represents an intermediary city on the path between i and j. This step is known as Floyd-Warshall's Algorithm.

  5. We return the value of D[start][end] where start and end are the source and destination cities respectively.

Code:

Here is the Python code for the above algorithm:

def minimumScore(numCities, cities, start, end):
    D = [[float('inf')] * numCities for _ in range(numCities)]
    
    for i in range(numCities):
        D[i][i] = 0
        
    for u, v, w in cities:
        D[u][v] = min(D[u][v], w)
        D[v][u] = min(D[v][u], w)
        
    for k in range(numCities):
        for i in range(numCities):
            for j in range(numCities):
                D[i][j] = min(D[i][j], max(D[i][k], D[k][j]))
                
    return D[start][end] if D[start][end] != float('inf') else -1

The function takes four arguments - the number of cities, the list of cities with their connecting edges and costs, the source city and the destination city. It returns the minimum score of the path between the source and destination cities.

Time Complexity:

The time complexity of the above algorithm is O(n^3) where n is the number of cities. This is because we have three nested loops of size n in the Floyd-Warshall's algorithm. Therefore, the algorithm may not be suitable for large input sizes.

Minimum Score Of A Path Between Two Cities Solution Code

1