12
12
"""
13
13
14
14
from collections import deque
15
- from typing import Dict , List , Optional
15
+ from typing import Optional
16
16
17
17
18
18
def bidirectional_search (
19
- graph : Dict [int , List [int ]], start : int , goal : int
20
- ) -> Optional [ List [ int ]] :
19
+ graph : dict [int , list [int ]], start : int , goal : int
20
+ ) -> list [ int ] | None :
21
21
"""
22
22
Perform bidirectional search on a graph to find the shortest path.
23
23
@@ -67,8 +67,8 @@ def bidirectional_search(
67
67
68
68
# Initialize forward and backward search dictionaries
69
69
# Each maps a node to its parent in the search
70
- forward_parents = {start : None }
71
- backward_parents = {goal : None }
70
+ forward_parents : dict [ int , int | None ] = {start : None }
71
+ backward_parents : dict [ int , int | None ] = {goal : None }
72
72
73
73
# Initialize forward and backward search queues
74
74
forward_queue = deque ([start ])
@@ -110,19 +110,19 @@ def bidirectional_search(
110
110
return None
111
111
112
112
# Construct path from start to intersection
113
- forward_path = []
114
- current = intersection
115
- while current is not None :
116
- forward_path .append (current )
117
- current = forward_parents [current ]
113
+ forward_path : list [ int ] = []
114
+ current_forward : int | None = intersection
115
+ while current_forward is not None :
116
+ forward_path .append (current_forward )
117
+ current_forward = forward_parents [current_forward ]
118
118
forward_path .reverse ()
119
119
120
120
# Construct path from intersection to goal
121
- backward_path = []
122
- current = backward_parents [intersection ]
123
- while current is not None :
124
- backward_path .append (current )
125
- current = backward_parents [current ]
121
+ backward_path : list [ int ] = []
122
+ current_backward : int | None = backward_parents [intersection ]
123
+ while current_backward is not None :
124
+ backward_path .append (current_backward )
125
+ current_backward = backward_parents [current_backward ]
126
126
127
127
# Return the complete path
128
128
return forward_path + backward_path
@@ -131,7 +131,7 @@ def bidirectional_search(
131
131
def main () -> None :
132
132
"""
133
133
Run example of bidirectional search algorithm.
134
-
134
+
135
135
Examples:
136
136
>>> main() # doctest: +NORMALIZE_WHITESPACE
137
137
Path from 0 to 11: [0, 1, 3, 7, 11]
0 commit comments