Skip to content

2492. Minimum Score of a Path Between Two Cities 👍

  • Time: $O(|V| + |E|)$
  • Space: $O(|V| + |E|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
 public:
  int minScore(int n, vector<vector<int>>& roads) {
    int ans = INT_MAX;
    vector<vector<pair<int, int>>> graph(n);  // graph[u] := [(v, distance)]
    queue<int> q{{0}};
    vector<bool> seen(n);
    seen[0] = true;

    for (const vector<int>& r : roads) {
      const int u = r[0] - 1;
      const int v = r[1] - 1;
      const int distance = r[2];
      graph[u].emplace_back(v, distance);
      graph[v].emplace_back(u, distance);
    }

    while (!q.empty()) {
      const int u = q.front();
      q.pop();
      for (const auto& [v, d] : graph[u]) {
        ans = min(ans, d);
        if (seen[v])
          continue;
        q.push(v);
        seen[v] = true;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
  public int minScore(int n, int[][] roads) {
    int ans = Integer.MAX_VALUE;
    List<Pair<Integer, Integer>>[] graph = new List[n]; // graph[u] := [(v, distance)]
    Queue<Integer> q = new ArrayDeque<>(List.of(0));
    boolean[] seen = new boolean[n];
    seen[0] = true;

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (final int[] r : roads) {
      final int u = r[0] - 1;
      final int v = r[1] - 1;
      final int distance = r[2];
      graph[u].add(new Pair<>(v, distance));
      graph[v].add(new Pair<>(u, distance));
    }

    while (!q.isEmpty()) {
      final int u = q.poll();
      for (Pair<Integer, Integer> pair : graph[u]) {
        final int v = pair.getKey();
        final int d = pair.getValue();
        ans = Math.min(ans, d);
        if (seen[v])
          continue;
        q.offer(v);
        seen[v] = true;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def minScore(self, n: int, roads: list[list[int]]) -> int:
    ans = math.inf
    graph = [[] for _ in range(n + 1)]  # graph[u] := [(v, distance)]
    q = collections.deque([1])
    seen = {1}

    for u, v, distance in roads:
      graph[u].append((v, distance))
      graph[v].append((u, distance))

    while q:
      u = q.popleft()
      for v, d in graph[u]:
        ans = min(ans, d)
        if v in seen:
          continue
        q.append(v)
        seen.add(v)

    return ans