LeetCode 2699: Modify Graph Edge Weights
Problem Description
Explanation:
To solve this problem, we can use Dijkstra's algorithm to find the shortest path from the source node to all other nodes in the graph. Then, we can iterate through all the edges with weight -1 and try assigning different positive weights to them in the range [1, 2 * 10^9] to see if we can achieve the target distance between the source and destination nodes.
- Implement Dijkstra's algorithm to find the shortest path from the source node to all other nodes.
- Iterate through all edges with weight -1 and try assigning different positive weights to them.
- For each assignment, recompute the shortest path using Dijkstra's algorithm.
- If we find a modification that results in the target distance between the source and destination nodes, return the modified edges.
Time Complexity: O(n^2 * log n) where n is the number of nodes Space Complexity: O(n)
Solutions
import java.util.*;
class Solution {
public int[][] findSolution(int n, int[][] edges, int source, int destination, int target) {
Map<Integer, List<int[]>> graph = new HashMap<>();
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
int w = edge[2];
graph.computeIfAbsent(u, k -> new ArrayList<>()).add(new int[]{v, w});
graph.computeIfAbsent(v, k -> new ArrayList<>()).add(new int[]{u, w});
}
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
pq.offer(new int[]{source, 0});
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[source] = 0;
while (!pq.isEmpty()) {
int[] curr = pq.poll();
int node = curr[0];
int distance = curr[1];
if (distance > dist[node]) continue;
for (int[] neighbor : graph.getOrDefault(node, new ArrayList<>())) {
int nextNode = neighbor[0];
int weight = neighbor[1];
if (dist[node] + weight < dist[nextNode]) {
dist[nextNode] = dist[node] + weight;
pq.offer(new int[]{nextNode, dist[nextNode]});
}
}
}
List<int[]> result = new ArrayList<>();
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
int w = edge[2];
if (w == -1) {
for (int i = 1; i <= 2 * target; i++) {
int originalWeight = dist[u] + dist[v];
int newWeight = dist[u] + i + dist[v];
if (newWeight == target) {
result.add(new int[]{u, v, i});
break;
}
}
} else {
result.add(new int[]{u, v, w});
}
}
return result.toArray(new int[0][]);
}
}
Loading editor...