Minimum Score of a Path Between Two Cities Problem
Description
LeetCode Problem 2492.
You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [a_i, b_i, distance_i] indicates that there is a bidirectional road between cities a_i and b_i with a distance equal to distance_i. The cities graph is not necessarily connected.
The score of a path between two cities is defined as the minimum distance of a road in this path.
Return the minimum possible score of a path between cities 1 and n.
Note:
- A path is a sequence of roads between two cities.
- It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and
nmultiple times along the path. - The test cases are generated such that there is at least one path between 1 and
n.
Example 1:

Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
Output: 5
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5.
It can be shown that no other path has less score.
Example 2:

Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]
Output: 2
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.
Constraints:
2 <= n <= 10^51 <= roads.length <= 10^5roads[i].length == 31 <= a_i, b_i <= na_i != b_i1 <= distance_i <= 10^4- There are no repeated edges.
- There is at least one path between
1andn.
Solution
Approach: DFS over the component
A path may revisit roads and cities, so any road in the connected component of city 1 can be used on some path from 1 to n (go there, take the road, come back). Cities 1 and n are guaranteed to be connected, so the answer is simply the smallest road weight in the component that contains city 1.
Build the adjacency lists, run a DFS from city 1, and take the minimum weight over every road seen.
Complexity: time O(n + m); space O(n + m).
from math import inf
class Solution:
def minScore(self, n: int, roads: List[List[int]]) -> int:
def dfs(a: int):
vis[a] = True
nonlocal ans
for b, w in g[a]:
ans = min(ans, w)
if not vis[b]:
dfs(b)
g = [[] for _ in range(n + 1)]
for a, b, w in roads:
g[a].append((b, w))
g[b].append((a, w))
ans = inf
vis = [False] * (n + 1)
dfs(1)
return ans