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 _theminimum possible score of a path between cities _1andn.
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 n multiple times along the path.
The test cases are generated such that there is at least one path between 1 and n.

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

Input: n =4, roads =[[1,2,2],[1,3,4],[3,4,7]]Output: 2Explanation: The path from city 1 to 4with the minimum score is:1->2->1->3->4. The score of this path ismin(2,2,4,7)=2.
Since you can revisit cities and roads, the minimum score is the smallest edge in the connected component containing city 1. Traverse all reachable cities from 1 and track the minimum edge.
import java.util.*;
classSolution {
publicintminScore(int n, int[][] roads) {
List<int[]>[] g =new List[n+1];
for (int i = 1; i <= n; i++) g[i]=new ArrayList<>();
for (int[] r : roads) {
g[r[0]].add(newint[]{r[1],r[2]});
g[r[1]].add(newint[]{r[0],r[2]});
}
boolean[] vis =newboolean[n+1];
int res = 10001;
Queue<Integer> q =new LinkedList<>(); q.add(1); vis[1]=true;
while (!q.isEmpty()) {
int u = q.poll();
for (int[] e : g[u]) {
int v = e[0], d = e[1];
res = Math.min(res,d);
if (!vis[v]) { vis[v]=true; q.add(v); }
}
}
return res;
}
}
classSolution {
funminScore(n: Int, roads: Array<IntArray>): Int {
val g = Array(n+1){mutableListOf<Pair<Int,Int>>()}
for (r in roads) {
g[r[0]].add(r[1] to r[2])
g[r[1]].add(r[0] to r[2])
}
val vis = BooleanArray(n+1)
var res = 10001val q = ArrayDeque<Int>()
q.add(1); vis[1]=truewhile (q.isNotEmpty()) {
val u = q.removeFirst()
for ((v,d) in g[u]) {
res = minOf(res,d)
if (!vis[v]) { vis[v]=true; q.add(v) }
}
}
return res
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from collections import deque,defaultdict
classSolution:
defminScore(self, n: int, roads: list[list[int]]) -> int:
g = defaultdict(list)
for a,b,d in roads:
g[a].append((b,d))
g[b].append((a,d))
vis = [False]*(n+1)
res =10001 q = deque([1]); vis[1]=Truewhile q:
u = q.popleft()
for v,d in g[u]:
res = min(res,d)
ifnot vis[v]: vis[v]=True; q.append(v)
return res