711092. Minimum Multiplications to reach End
Medium
Minimum Multiplications to reach End
Summary
Given a list of integers representing the cost of traveling between two cities, find the minimum number of multiplications needed to travel from the starting city to the ending city. The graph is assumed to be directed and weighted.
Detailed Explanation
The problem can be solved using Breadth-First Search (BFS) algorithm. We will create a queue and enqueue all nodes at distance 1 from the source node. Then, we will dequeue each node, add its neighbors to the queue, and update their distances accordingly.
Here is a step-by-step breakdown of the solution:
- Initialize an array
distof sizen+1, wherenis the number of cities, to store the minimum distance from the source city to each city. Set all values indistto infinity except for the source node, which is set to 0. - Create a queue and enqueue the source node.
- While the queue is not empty:
- Dequeue a node with minimum distance.
- For each neighbor of the dequeued node that has not been visited yet:
- Update its distance by adding the cost of traveling from the dequeued node to the neighbor.
- If the updated distance is less than the current value in
dist, updatedistand enqueue the neighbor.
- The minimum number of multiplications needed to travel from the source city to the ending city is stored in
dist[n].
Time complexity: O(n + m), where n is the number of cities and m is the number of edges.
Space complexity: O(n), for storing the distance array and the queue.
Optimized Solutions
Java
import java.util.*;
class Main {
public static int minMultiplications(int[] cost) {
int n = cost.length;
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[0] = 0;
Queue<Integer> queue = new LinkedList<>();
queue.add(0);
while (!queue.isEmpty()) {
int node = queue.poll();
for (int i = 1; i < n; i++) {
if (cost[node] + cost[i] > cost[i]) continue;
if (dist[node] + cost[i] < dist[i]) {
dist[i] = dist[node] + cost[i];
queue.add(i);
}
}
}
return dist[n-1];
}
}