Leetcode 2492: Minimum Score of a Path Between Two Cities

grid47
grid47
Exploring patterns and algorithms
Mar 2, 2024 7 min read

You are given a set of cities, each connected by bidirectional roads. Each road has a distance, and the score of a path between two cities is defined as the minimum distance of any road on that path. The task is to find the minimum score of a path between city 1 and city n. You are allowed to visit the cities multiple times, and the roads may be repeated.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer n representing the number of cities, and a 2D array roads, where each road is represented as [ai, bi, distancei] meaning there is a bidirectional road between city ai and bi with distance distancei.
Example: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
Constraints:
• 2 <= n <= 10^5
• 1 <= roads.length <= 10^5
• 1 <= ai, bi <= n
• 1 <= distancei <= 10^4
• There are no repeated edges.
• There is at least one path between city 1 and city n.
Output: Return the minimum possible score of a path between city 1 and city n. If no path exists, return -1.
Example: Output: 5
Constraints:
• The score is calculated by considering the minimum distance in the path between city 1 and city n.
Goal: The goal is to find the minimum score of a path between cities 1 and n by traversing the graph of cities and roads.
Steps:
• 1. Construct an adjacency list for the graph.
• 2. Use BFS or DFS starting from city 1 to visit all connected cities.
• 3. Track the minimum distance of any road encountered during traversal.
• 4. Return the minimum score of the path when city n is reached.
Goal: Ensure that all roads are bidirectional, and the graph is connected between city 1 and city n.
Steps:
• The graph is guaranteed to be connected between cities 1 and n.
• No duplicate roads exist in the input.
Assumptions:
• The input graph is connected for cities 1 and n.
• The roads form a connected graph between cities, ensuring that there is at least one path between city 1 and city n.
Input: Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
Explanation: The cities can be connected through the path 1 -> 2 -> 4 with the minimum score being min(9,5), which is 5.

Input: Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]
Explanation: The minimum score of the path from city 1 to city 4 is 2, which is the minimum distance encountered in the path 1 -> 2 -> 1 -> 3 -> 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus