Skip to content

Commit 8ca2d9f

Browse files
Create zero_one_bfs.java (#6560)
* Create zero_one_bfs.java * Rename zero_one_bfs.java to ZeroOneBfs.java * Update ZeroOneBfs.java * Update ZeroOneBfs.java * Create ZeroOneBfsTest.java * Update ZeroOneBfsTest.java --------- Co-authored-by: a <[email protected]>
1 parent 9484c7e commit 8ca2d9f

File tree

2 files changed

+145
-0
lines changed

2 files changed

+145
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package com.thealgorithms.graph;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.Arrays;
5+
import java.util.Deque;
6+
import java.util.List;
7+
8+
/**
9+
* 0-1 BFS for shortest paths on graphs with edges weighted 0 or 1.
10+
*
11+
* <p>Time Complexity: O(V + E). Space Complexity: O(V).
12+
*
13+
* <p>References:
14+
* <ul>
15+
* <li>https://cp-algorithms.com/graph/01_bfs.html</li>
16+
* </ul>
17+
*/
18+
public final class ZeroOneBfs {
19+
20+
private ZeroOneBfs() {
21+
// Utility class; do not instantiate.
22+
}
23+
24+
/**
25+
* Computes shortest distances from {@code src} in a graph whose edges have weight 0 or 1.
26+
*
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
34+
*/
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+
}
39+
int[] dist = new int[n];
40+
Arrays.fill(dist, Integer.MAX_VALUE);
41+
Deque<Integer> dq = new ArrayDeque<>();
42+
43+
dist[src] = 0;
44+
dq.addFirst(src);
45+
46+
while (!dq.isEmpty()) {
47+
int u = dq.pollFirst();
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+
}
56+
int v = e[0];
57+
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+
}
64+
int nd = dist[u] + w;
65+
if (nd < dist[v]) {
66+
dist[v] = nd;
67+
if (w == 0) {
68+
dq.addFirst(v);
69+
} else {
70+
dq.addLast(v);
71+
}
72+
}
73+
}
74+
}
75+
return dist;
76+
}
77+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.thealgorithms.graph;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import java.util.ArrayList;
7+
import java.util.List;
8+
import org.junit.jupiter.api.Test;
9+
10+
class ZeroOneBfsTest {
11+
12+
// Helper to build adjacency list with capacity n
13+
private static List<List<int[]>> makeAdj(int n) {
14+
List<List<int[]>> adj = new ArrayList<>(n);
15+
for (int i = 0; i < n; i++) {
16+
adj.add(new ArrayList<>());
17+
}
18+
return adj;
19+
}
20+
21+
@Test
22+
void simpleLineGraph() {
23+
int n = 4;
24+
List<List<int[]>> adj = makeAdj(n);
25+
// 0 --0--> 1 --1--> 2 --0--> 3
26+
adj.get(0).add(new int[] {1, 0});
27+
adj.get(1).add(new int[] {2, 1});
28+
adj.get(2).add(new int[] {3, 0});
29+
30+
int[] dist = ZeroOneBfs.shortestPaths(n, adj, 0);
31+
assertArrayEquals(new int[] {0, 0, 1, 1}, dist);
32+
}
33+
34+
@Test
35+
void parallelEdgesPreferZero() {
36+
int n = 3;
37+
List<List<int[]>> adj = makeAdj(n);
38+
// Two edges 0->1: weight 1 and weight 0. Algorithm should choose 0.
39+
adj.get(0).add(new int[] {1, 1});
40+
adj.get(0).add(new int[] {1, 0});
41+
adj.get(1).add(new int[] {2, 1});
42+
43+
int[] dist = ZeroOneBfs.shortestPaths(n, adj, 0);
44+
assertArrayEquals(new int[] {0, 0, 1}, dist);
45+
}
46+
47+
@Test
48+
void unreachableNodes() {
49+
int n = 3;
50+
List<List<int[]>> adj = makeAdj(n);
51+
adj.get(0).add(new int[] {1, 0});
52+
int[] dist = ZeroOneBfs.shortestPaths(n, adj, 0);
53+
// node 2 unreachable -> Integer.MAX_VALUE
54+
assertArrayEquals(new int[] {0, 0, Integer.MAX_VALUE}, dist);
55+
}
56+
57+
@Test
58+
void invalidArgs() {
59+
int n = 2;
60+
List<List<int[]>> adj = makeAdj(n);
61+
// invalid weight
62+
adj.get(0).add(new int[] {1, 2});
63+
assertThrows(IllegalArgumentException.class, () -> ZeroOneBfs.shortestPaths(n, adj, 0));
64+
// invalid src
65+
assertThrows(IllegalArgumentException.class, () -> ZeroOneBfs.shortestPaths(n, adj, -1));
66+
assertThrows(IllegalArgumentException.class, () -> ZeroOneBfs.shortestPaths(n, adj, 2));
67+
}
68+
}

0 commit comments

Comments
 (0)