Skip to content

Commit 8780e65

Browse files
Update ZeroOneBfs.java
1 parent 44df65a commit 8780e65

File tree

1 file changed

+32
-12
lines changed

1 file changed

+32
-12
lines changed

src/main/java/com/thealgorithms/graph/ZeroOneBfs.java

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
package com.thealgorithms.graphs;
1+
package com.thealgorithms.graph;
22

3-
import java.util.Deque;
43
import java.util.ArrayDeque;
54
import java.util.Arrays;
5+
import java.util.Deque;
66
import java.util.List;
77

88
/**
9-
* 0-1 BFS for shortest paths on graphs with 0/1 edge weights.
9+
* 0-1 BFS for shortest paths on graphs with edges weighted 0 or 1.
1010
*
11-
* <p>Time: O(V + E). Space: O(V).
11+
* <p>Time Complexity: O(V + E). Space Complexity: O(V).
1212
*
1313
* <p>References:
1414
* <ul>
@@ -18,29 +18,49 @@
1818
public final class ZeroOneBfs {
1919

2020
private ZeroOneBfs() {
21-
// utility class
21+
// Utility class; do not instantiate.
2222
}
2323

2424
/**
25-
* Computes shortest distances from {@code src} in a graph with edges weighted 0 or 1.
25+
* Computes shortest distances from {@code src} in a graph whose edges have weight 0 or 1.
2626
*
27-
* @param n number of vertices labeled [0..n-1]
28-
* @param edges adjacency list where each entry is (to, weight) with weight ∈ {0,1}
29-
* @param src source vertex
30-
* @return distances array; {@code Integer.MAX_VALUE} if unreachable
27+
* @param n the number of vertices, labeled {@code 0..n-1}
28+
* @param adj adjacency list; for each vertex u, {@code adj.get(u)} is a list of pairs
29+
* {@code (v, w)} where {@code v} is a neighbor and {@code w} is 0 or 1
30+
* @param src the source vertex
31+
* @return an array of distances; {@code Integer.MAX_VALUE} denotes unreachable
32+
* @throws IllegalArgumentException if {@code n < 0}, {@code src} is out of range,
33+
* or any edge has weight other than 0 or 1
3134
*/
32-
public static int[] shortestPaths(int n, List<List<int[]>> edges, int src) {
35+
public static int[] shortestPaths(int n, List<List<int[]>> adj, int src) {
36+
if (n < 0 || src < 0 || src >= n) {
37+
throw new IllegalArgumentException("Invalid n or src");
38+
}
3339
int[] dist = new int[n];
3440
Arrays.fill(dist, Integer.MAX_VALUE);
3541
Deque<Integer> dq = new ArrayDeque<>();
42+
3643
dist[src] = 0;
3744
dq.addFirst(src);
3845

3946
while (!dq.isEmpty()) {
4047
int u = dq.pollFirst();
41-
for (int[] e : edges.get(u)) {
48+
List<int[]> edges = adj.get(u);
49+
if (edges == null) {
50+
continue;
51+
}
52+
for (int[] e : edges) {
53+
if (e == null || e.length < 2) {
54+
continue;
55+
}
4256
int v = e[0];
4357
int w = e[1];
58+
if (v < 0 || v >= n) {
59+
continue; // ignore bad edges
60+
}
61+
if (w != 0 && w != 1) {
62+
throw new IllegalArgumentException("Edge weight must be 0 or 1");
63+
}
4464
int nd = dist[u] + w;
4565
if (nd < dist[v]) {
4666
dist[v] = nd;

0 commit comments

Comments
 (0)