From a921f8153d3c4e1cf9a399e51a4f76555478c362 Mon Sep 17 00:00:00 2001 From: Amal Bijoy Date: Tue, 7 Apr 2026 11:36:35 +0530 Subject: [PATCH] Add non-negative edge precheck to dijkstra --- Data-Structures/Graphs/Dijkstra.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) 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);