Skip to content

Commit 6a9916f

Browse files
solves #1514: Path with Maximum Probability in java
1 parent 1bb0219 commit 6a9916f

File tree

3 files changed

+109
-54
lines changed

3 files changed

+109
-54
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,7 @@
606606
| 1502 | [Can Make Arithmetic Progression From Sequence](https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence) | [![Java](assets/java.png)](src/CanMakeArithmeticProgressionFromSequence.java) | |
607607
| 1507 | [Reformat Date](https://leetcode.com/problems/reformat-date) | [![Java](assets/java.png)](src/ReformatDate.java) | |
608608
| 1512 | [Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs) | [![Java](assets/java.png)](src/NumberOfGoodPairs.java) | |
609+
| 1514 | [Path with Maximum Probability](https://leetcode.com/problems/path-with-maximum-probability) | [![Java](assets/java.png)](src/PathWithMaximumProbability.java) | |
609610
| 1518 | [Water Bottles](https://leetcode.com/problems/water-bottles) | [![Java](assets/java.png)](src/WaterBottles.java) | |
610611
| 1523 | [Count Odd Numbers In Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range) | [![Java](assets/java.png)](src/CountOddNumbersInIntervalRange.java) | |
611612
| 1528 | [Shuffle Strings](https://leetcode.com/problems/shuffle-string) | [![Java](assets/java.png)](src/ShuffleString.java) | |

Diff for: src/HelloWorld.java

+42-54
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,66 @@
1-
// T: O(N + E alp(N))
2-
// S: O(N)
1+
// T: O(V + EllogV)
2+
// S: O(E + V)
33

4-
import java.security.cert.Certificate;
5-
import java.util.ArrayList;
6-
import java.util.LinkedList;
7-
import java.util.List;
4+
import java.util.Comparator;
5+
import java.util.HashMap;
6+
import java.util.HashSet;
7+
import java.util.Map;
8+
import java.util.PriorityQueue;
89
import java.util.Queue;
9-
10+
import java.util.Set;
1011

1112

1213
public class HelloWorld {
13-
private static final List<List<Integer>> DIRECTIONS = List.of(
14-
List.of(1, 0),
15-
List.of(0, 1),
16-
List.of(-1, 0),
17-
List.of(0, -1)
18-
);
14+
private static final record Pair(int vertex, int distance) {}
15+
16+
public int networkDelayTime(int[][] times, int n, int k) {
17+
final Map<Integer, Map<Integer, Integer>> graph = createGraph(times);
18+
final Map<Integer, Integer> distances = new HashMap<>();
19+
final Queue<Pair> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a.distance));
1920

20-
public int orangesRotting(int[][] grid) {
21-
final Queue<int[]> queue = new LinkedList<>();
22-
addRottenOrangesToQueue(queue, grid);
23-
int maxTime = 0;
21+
minHeap.add(new Pair(k, 0));
2422

25-
while (!queue.isEmpty()) {
26-
final int[] info = queue.poll();
27-
final int row = info[0], column = info[1], time = info[2];
23+
while (!minHeap.isEmpty()) {
24+
final Pair pair = minHeap.poll();
25+
final int vertex = pair.vertex, distanceToVertex = pair.distance;
26+
final int currentVertexTime = distances.getOrDefault(vertex, Integer.MAX_VALUE);
2827

29-
if (grid[row][column] == 0) {
28+
if (currentVertexTime < distanceToVertex) {
3029
continue;
3130
}
3231

33-
maxTime = Math.max(time, maxTime);
34-
grid[row][column] = 0;
35-
36-
for (int[] neighbour : getNeighbours(grid, row, column)) {
37-
queue.add(new int[] { neighbour[0], neighbour[1], time + 1});
38-
}
39-
}
32+
distances.put(vertex, distanceToVertex);
4033

41-
if (containsFreshOranges(grid)) {
42-
return -1;
43-
}
44-
return maxTime;
45-
}
34+
for (Map.Entry<Integer, Integer> entry : graph.getOrDefault(pair.vertex, new HashMap<>()).entrySet()) {
35+
final int neighbour = entry.getKey(), distance = entry.getValue();
36+
final int currentMinDistance = distances.getOrDefault(neighbour, Integer.MAX_VALUE);
37+
final int minDistance = Math.min(currentMinDistance, distances.get(pair.vertex) + distance);
4638

47-
private static boolean containsFreshOranges(int[][] grid) {
48-
for (int[] row : grid) {
49-
for (int orange : row) {
50-
if (orange == 1) {
51-
return true;
39+
if (minDistance < currentMinDistance) {
40+
distances.put(neighbour, minDistance);
41+
minHeap.add(new Pair(neighbour, minDistance));
5242
}
5343
}
5444
}
55-
return false;
45+
46+
return minTimeRequired(distances, n);
5647
}
5748

58-
private static void addRottenOrangesToQueue(Queue<int[]> queue, int[][] grid) {
59-
for(int row = 0 ; row < grid.length ; row++) {
60-
for (int column = 0 ; column < grid[0].length ; column++) {
61-
if (grid[row][column] == 2) {
62-
queue.add(new int[] { row, column, 0 });
63-
}
64-
}
49+
private static Map<Integer, Map<Integer, Integer>> createGraph(int[][] edges) {
50+
final Map<Integer, Map<Integer, Integer>> result = new HashMap<>();
51+
for (int[] edge : edges) {
52+
final int from = edge[0], to = edge[1], weight = edge[2];
53+
final Map<Integer, Integer> weights = result.getOrDefault(from, new HashMap<>());
54+
weights.put(to, weight);
55+
result.putIfAbsent(from, weights);
6556
}
57+
return result;
6658
}
6759

68-
private static List<int[]> getNeighbours(int[][] grid, int row, int column) {
69-
final List<int[]> result = new ArrayList<>();
70-
for (List<Integer> direction : DIRECTIONS) {
71-
final int r = row + direction.get(0), c = column + direction.get(1);
72-
if (r >= 0 && r < grid.length && c >= 0 && c < grid[0].length && grid[r][c] == 1) {
73-
result.add(new int[] {r, c});
74-
}
60+
private static int minTimeRequired(Map<Integer, Integer> distances, int n) {
61+
if (distances.size() != n) {
62+
return -1;
7563
}
76-
return result;
64+
return distances.values().stream().max(Integer::compareTo).get();
7765
}
7866
}

Diff for: src/PathWithMaximumProbability.java

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// https://leetcode.com/problems/path-with-maximum-probability
2+
// T: O(E + N + E logN)
3+
// S: O(E + N)
4+
5+
import java.util.Comparator;
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
import java.util.PriorityQueue;
9+
import java.util.Queue;
10+
11+
public class PathWithMaximumProbability {
12+
private record Pair(int vertex, double probability) {}
13+
14+
public static double maxProbability(int n, int[][] edges, double[] probabilities, int start, int end) {
15+
final Map<Integer, Map<Integer, Double>> graph = createGraph(edges, probabilities);
16+
final Map<Integer, Double> distances = dijkstra(graph, start, end);
17+
return distances.getOrDefault(end, 0.0);
18+
}
19+
20+
private static Map<Integer, Map<Integer, Double>> createGraph(int[][] edges, double[] probabilities) {
21+
final Map<Integer, Map<Integer, Double>> graph = new HashMap<>();
22+
int k = 0;
23+
for (int[] edge : edges) {
24+
final int from = edge[0], to = edge[1];
25+
final double weight = probabilities[k++];
26+
final Map<Integer, Double> fromNeighbours = graph.getOrDefault(from, new HashMap<>());
27+
final Map<Integer, Double> toNeighbours = graph.getOrDefault(to, new HashMap<>());
28+
fromNeighbours.put(to, weight);
29+
toNeighbours.put(from, weight);
30+
graph.putIfAbsent(from, fromNeighbours);
31+
graph.putIfAbsent(to, toNeighbours);
32+
}
33+
return graph;
34+
}
35+
36+
private static Map<Integer, Double> dijkstra(Map<Integer, Map<Integer, Double>> graph, int start, int end) {
37+
final Map<Integer, Double> distances = new HashMap<>();
38+
final Queue<Pair> minHeap = new PriorityQueue<>(Comparator.comparingDouble(a -> a.probability));
39+
minHeap.add(new Pair(start, 1));
40+
distances.put(start, 1.0);
41+
42+
while (!minHeap.isEmpty()) {
43+
final Pair pair = minHeap.poll();
44+
45+
if (pair.vertex == end) {
46+
break;
47+
}
48+
49+
for (Map.Entry<Integer, Double> neighbour : graph.getOrDefault(pair.vertex, new HashMap<>()).entrySet()) {
50+
final int edgeVertex = neighbour.getKey();
51+
final double edgeWeight = neighbour.getValue();
52+
final double currentProbability = distances.getOrDefault(edgeVertex, 0.0);
53+
final double edgeProbability = Math.max(
54+
currentProbability,
55+
pair.probability * edgeWeight
56+
);
57+
if (edgeProbability > currentProbability) {
58+
distances.put(edgeVertex, edgeProbability);
59+
minHeap.add(new Pair(edgeVertex, edgeProbability));
60+
}
61+
}
62+
}
63+
64+
return distances;
65+
}
66+
}

0 commit comments

Comments
 (0)