Skip to content

Commit 73b29d7

Browse files
Create ZeroOneBfsTest.java
1 parent 8780e65 commit 73b29d7

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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,
64+
() -> ZeroOneBfs.shortestPaths(n, adj, 0));
65+
// invalid src
66+
assertThrows(IllegalArgumentException.class,
67+
() -> ZeroOneBfs.shortestPaths(n, adj, -1));
68+
assertThrows(IllegalArgumentException.class,
69+
() -> ZeroOneBfs.shortestPaths(n, adj, 2));
70+
}
71+
}

0 commit comments

Comments
 (0)