MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / modifiedGraphEdges

Method modifiedGraphEdges

modifiedGraphEdges.java:6–50  ·  view source on GitHub ↗
(int n,int[][] edges,int source,int destination,int target)

Source from the content-addressed store, hash-verified

4 int INF = (int)1e9;
5
6 public int[][] modifiedGraphEdges(int n,int[][] edges,int source,int destination,int target) {
7 //form the adjlist
8 // init
9 graph = new ArrayList[n];
10 for (int i = 0; i < n; i++) {
11 graph[i] = new ArrayList<>();
12 }
13 // exclude node with -1 value;
14 for (int[] edge : edges) {
15 if (edge[2] != -1) {
16 graph[edge[0]].add(new int[] { edge[1], edge[2] });
17 graph[edge[1]].add(new int[] { edge[0], edge[2] });
18 }
19 }
20 int minDist = runDijkstra(n, source, destination);
21 //not possible to meet target
22 if (minDist < target) {
23 return new int[0][0];
24 }
25 // we don't need -1 weighted edges
26 if (minDist == target) {
27 for (int[] edge : edges) {
28 if(edge[2] == -1){
29 edge[2] = INF;
30 }
31 }
32 return edges;
33 }
34 // if minDist > target (we can further reduce the minDist)
35 boolean matchesTarget = false;
36 for (int[] edge : edges) {
37 if (edge[2] != -1) continue;
38 edge[2] = matchesTarget ? INF : 1;
39 graph[edge[0]].add(new int[] { edge[1], edge[2] });
40 graph[edge[1]].add(new int[] { edge[0], edge[2] });
41 if (!matchesTarget) {
42 int newDistance = runDijkstra(n, source, destination);
43 if (newDistance <= target) {
44 matchesTarget = true;
45 edge[2] += target - newDistance;
46 }
47 }
48 }
49 return matchesTarget ? edges : new int[0][0];
50 }
51
52 // Dijkstra's algorithm to find the shortest path from source to destination
53 private int runDijkstra(int n, int source, int destination) {

Callers

nothing calls this directly

Calls 2

runDijkstraMethod · 0.95
addMethod · 0.45

Tested by

no test coverage detected