Skip to content

Commit a99ddc2

Browse files
Create zero_one_bfs.java
1 parent f9a9ccb commit a99ddc2

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.thealgorithms.graphs;
2+
3+
import java.util.*;
4+
5+
/**
6+
* 0-1 BFS for shortest paths on graphs with 0/1 edge weights.
7+
*
8+
* <p>Time: O(V + E). Space: O(V).
9+
*
10+
* <p>References:
11+
* <ul>
12+
* <li>https://cp-algorithms.com/graph/01_bfs.html</li>
13+
* </ul>
14+
*/
15+
public final class ZeroOneBfs {
16+
17+
private ZeroOneBfs() {
18+
// utility class
19+
}
20+
21+
/**
22+
* Computes shortest distances from {@code src} in a graph with edges weighted 0 or 1.
23+
*
24+
* @param n number of vertices labeled [0..n-1]
25+
* @param edges adjacency list where each entry is (to, weight) with weight ∈ {0,1}
26+
* @param src source vertex
27+
* @return distances array; {@code Integer.MAX_VALUE} if unreachable
28+
*/
29+
public static int[] shortestPaths(int n, List<List<int[]>> edges, int src) {
30+
int[] dist = new int[n];
31+
Arrays.fill(dist, Integer.MAX_VALUE);
32+
Deque<Integer> dq = new ArrayDeque<>();
33+
dist[src] = 0;
34+
dq.addFirst(src);
35+
36+
while (!dq.isEmpty()) {
37+
int u = dq.pollFirst();
38+
for (int[] e : edges.get(u)) {
39+
int v = e[0], w = e[1];
40+
int nd = dist[u] + w;
41+
if (nd < dist[v]) {
42+
dist[v] = nd;
43+
if (w == 0) {
44+
dq.addFirst(v);
45+
} else {
46+
dq.addLast(v);
47+
}
48+
}
49+
}
50+
}
51+
return dist;
52+
}
53+
}

0 commit comments

Comments
 (0)