Description
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] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. 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
1andnmultiple times along the path. - The test cases are generated such that there is at least one path between
1andn.
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 <= 1051 <= roads.length <= 105roads[i].length == 31 <= ai, bi <= nai != bi1 <= distancei <= 104- There are no repeated edges.
- There is at least one path between
1andn.
Solutions
Good enough solution for around 45 minutes of free time. An optimal solution for this problem would be using the union-find algorithm.
Language: javascript(2026-07-04 10:11)DONE
CPU Performance80.00%
Memory Performance64.00%
/**
* @param {number} n
* @param {number[][]} roads
* @return {number}
*/
var minScore = function(n, roads) {
const map = new Map();
const arr = new Array(n + 1).fill(Infinity);
for (let i = 1; i <= n; i++) {
map.set(i, new Set());
}
for (const [a, b, dist] of roads) {
map.get(a).add(b);
map.get(b).add(a);
arr[a] = Math.min(arr[a], dist);
arr[b] = Math.min(arr[b], dist);
}
const seen = Array(n + 1).fill(false);
seen[1] = true;
const dfs = (node) => {
let min = arr[node];
for (const con of map.get(node)) {
if (!seen[con]) {
seen[con] = true;
min = Math.min(min, dfs(con));
}
}
return min;
};
return dfs(1);
};