diff --git a/Data-Structures/Graphs/Dijkstra.java b/Data-Structures/Graphs/Dijkstra.java index f37120a..5113474 100644 --- a/Data-Structures/Graphs/Dijkstra.java +++ b/Data-Structures/Graphs/Dijkstra.java @@ -21,7 +21,21 @@ static void addDirectedEdge(ArrayList> adj, int u, int v, int w adj.get(u).add(new int[]{v, w}); } + /** + * Computes shortest paths from {@code src} with Dijkstra's algorithm. + * + *

Precondition: all edge weights in {@code adj} must be non-negative. + */ static long[] dijkstra(ArrayList> adj, int src) { + for (ArrayList edges : adj) { + for (int[] edge : edges) { + int w = edge[1]; + if (w < 0) { + throw new IllegalArgumentException("Dijkstra requires non-negative edge weights"); + } + } + } + int n = adj.size(); long[] dist = new long[n]; Arrays.fill(dist, Long.MAX_VALUE);