|
14 | 14 | from collections import deque |
15 | 15 |
|
16 | 16 |
|
| 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 | + |
17 | 36 | def bidirectional_search( |
18 | 37 | graph: dict[int, list[int]], start: int, goal: int |
19 | 38 | ) -> list[int] | None: |
@@ -79,30 +98,13 @@ def bidirectional_search( |
79 | 98 | # Continue until both queues are empty or an intersection is found |
80 | 99 | while forward_queue and backward_queue and intersection is None: |
81 | 100 | # 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) |
93 | 102 |
|
94 | 103 | # 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) |
106 | 108 |
|
107 | 109 | # If no intersection found, there's no path |
108 | 110 | if intersection is None: |
|
0 commit comments