Skip to content

Commit b21086d

Browse files
Update bidirectional_search.py
1 parent 4b350c3 commit b21086d

1 file changed

Lines changed: 24 additions & 22 deletions

File tree

graphs/bidirectional_search.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,25 @@
1414
from collections import deque
1515

1616

17+
def expand_search(graph: dict[int, list[int]], queue: deque[int], parents: dict[int, int | None], opposite_direction_parents: dict[int, int | None]) -> int | None:
18+
if not queue:
19+
return None
20+
21+
current = queue.popleft()
22+
for neighbor in graph[current]:
23+
if neighbor in parents:
24+
continue
25+
26+
parents[neighbor] = current
27+
queue.append(neighbor)
28+
29+
# Check if this creates an intersection
30+
if neighbor in opposite_direction_parents:
31+
return neighbor
32+
33+
return None
34+
35+
1736
def bidirectional_search(
1837
graph: dict[int, list[int]], start: int, goal: int
1938
) -> list[int] | None:
@@ -79,30 +98,13 @@ def bidirectional_search(
7998
# Continue until both queues are empty or an intersection is found
8099
while forward_queue and backward_queue and intersection is None:
81100
# Expand forward search
82-
if forward_queue:
83-
current = forward_queue.popleft()
84-
for neighbor in graph[current]:
85-
if neighbor not in forward_parents:
86-
forward_parents[neighbor] = current
87-
forward_queue.append(neighbor)
88-
89-
# Check if this creates an intersection
90-
if neighbor in backward_parents:
91-
intersection = neighbor
92-
break
101+
intersection = expand_search(graph=graph, queue=forward_queue, parents=forward_parents, opposite_direction_parents=backward_parents)
93102

94103
# If no intersection found, expand backward search
95-
if intersection is None and backward_queue:
96-
current = backward_queue.popleft()
97-
for neighbor in graph[current]:
98-
if neighbor not in backward_parents:
99-
backward_parents[neighbor] = current
100-
backward_queue.append(neighbor)
101-
102-
# Check if this creates an intersection
103-
if neighbor in forward_parents:
104-
intersection = neighbor
105-
break
104+
if intersection is not None:
105+
break
106+
107+
intersection = expand_search(graph=graph, queue=backward_queue, parents=backward_parents, opposite_direction_parents=forward_parents)
106108

107109
# If no intersection found, there's no path
108110
if intersection is None:

0 commit comments

Comments
 (0)