Skip to content

Commit bc05bce

Browse files
authored
Refactor BidirectionalBFS class for improved readability
1 parent bca2f22 commit bc05bce

File tree

1 file changed

+18
-40
lines changed

1 file changed

+18
-40
lines changed

src/main/java/com/thealgorithms/datastructures/graphs/BidirectionalBFS.java

Lines changed: 18 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,8 @@
1616
*
1717
* Wikipedia reference: https://en.wikipedia.org/wiki/Bidirectional_search
1818
*/
19+
public class BidirectionalBFS {
1920

20-
public class BidirectionalBFS
21-
{
2221
/**
2322
* Checks if a path exists between start and goal using bidirectional BFS.
2423
*
@@ -28,13 +27,11 @@ public class BidirectionalBFS
2827
* @return true if a path exists, false otherwise
2928
*/
3029
public static boolean bidirectionalBFS(
31-
Map<Integer, List<Integer>> graph,
32-
int start,
33-
int goal
34-
)
35-
{
36-
if (start == goal)
37-
{
30+
Map<Integer, List<Integer>> graph,
31+
int start,
32+
int goal
33+
) {
34+
if (start == goal) {
3835
return true;
3936
}
4037

@@ -50,27 +47,13 @@ public static boolean bidirectionalBFS(
5047
visitedStart.add(start);
5148
visitedGoal.add(goal);
5249

53-
while (!queueStart.isEmpty() && !queueGoal.isEmpty())
54-
{
50+
while (!queueStart.isEmpty() && !queueGoal.isEmpty()) {
5551
// Expand from start side
56-
if (expandFrontier(
57-
graph,
58-
queueStart,
59-
visitedStart,
60-
visitedGoal
61-
))
62-
{
52+
if (expandFrontier(graph, queueStart, visitedStart, visitedGoal)) {
6353
return true;
6454
}
65-
6655
// Expand from goal side
67-
if (expandFrontier(
68-
graph,
69-
queueGoal,
70-
visitedGoal,
71-
visitedStart
72-
))
73-
{
56+
if (expandFrontier(graph, queueGoal, visitedGoal, visitedStart)) {
7457
return true;
7558
}
7659
}
@@ -88,24 +71,19 @@ public static boolean bidirectionalBFS(
8871
* @return true if the frontiers meet, false otherwise
8972
*/
9073
private static boolean expandFrontier(
91-
Map<Integer, List<Integer>> graph,
92-
Queue<Integer> queue,
93-
Set<Integer> visitedThisSide,
94-
Set<Integer> visitedOtherSide
95-
)
96-
{
74+
Map<Integer, List<Integer>> graph,
75+
Queue<Integer> queue,
76+
Set<Integer> visitedThisSide,
77+
Set<Integer> visitedOtherSide
78+
) {
9779
int size = queue.size();
98-
for (int i = 0; i < size; i++)
99-
{
80+
for (int i = 0; i < size; i++) {
10081
int current = queue.poll();
101-
for (int neighbor : graph.getOrDefault(current, new ArrayList<>()))
102-
{
103-
if (visitedOtherSide.contains(neighbor))
104-
{
82+
for (int neighbor : graph.getOrDefault(current, new ArrayList<>())) {
83+
if (visitedOtherSide.contains(neighbor)) {
10584
return true;
10685
}
107-
if (!visitedThisSide.contains(neighbor))
108-
{
86+
if (!visitedThisSide.contains(neighbor)) {
10987
visitedThisSide.add(neighbor);
11088
queue.add(neighbor);
11189
}

0 commit comments

Comments
 (0)