MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / bidirectional_search

Function bidirectional_search

graphs/bidirectional_search.py:49–148  ·  view source on GitHub ↗

Perform bidirectional search on a graph to find the shortest path. Args: graph: A dictionary where keys are nodes and values are lists of adjacent nodes start: The starting node goal: The target node Returns: A list representing the path from start to g

(
    graph: dict[int, list[int]], start: int, goal: int
)

Source from the content-addressed store, hash-verified

47
48
49def bidirectional_search(
50 graph: dict[int, list[int]], start: int, goal: int
51) -> list[int] | None:
52 """
53 Perform bidirectional search on a graph to find the shortest path.
54
55 Args:
56 graph: A dictionary where keys are nodes and values are lists of adjacent nodes
57 start: The starting node
58 goal: The target node
59
60 Returns:
61 A list representing the path from start to goal, or None if no path exists
62
63 Examples:
64 >>> graph = {
65 ... 0: [1, 2],
66 ... 1: [0, 3, 4],
67 ... 2: [0, 5, 6],
68 ... 3: [1, 7],
69 ... 4: [1, 8],
70 ... 5: [2, 9],
71 ... 6: [2, 10],
72 ... 7: [3, 11],
73 ... 8: [4, 11],
74 ... 9: [5, 11],
75 ... 10: [6, 11],
76 ... 11: [7, 8, 9, 10],
77 ... }
78 >>> bidirectional_search(graph=graph, start=0, goal=11)
79 [0, 1, 3, 7, 11]
80 >>> bidirectional_search(graph=graph, start=5, goal=5)
81 [5]
82 >>> disconnected_graph = {
83 ... 0: [1, 2],
84 ... 1: [0],
85 ... 2: [0],
86 ... 3: [4],
87 ... 4: [3],
88 ... }
89 >>> bidirectional_search(graph=disconnected_graph, start=0, goal=3) is None
90 True
91 """
92 if start == goal:
93 return [start]
94
95 # Check if start and goal are in the graph
96 if start not in graph or goal not in graph:
97 return None
98
99 # Initialize forward and backward search dictionaries
100 # Each maps a node to its parent in the search
101 forward_parents: dict[int, int | None] = {start: None}
102 backward_parents: dict[int, int | None] = {goal: None}
103
104 # Initialize forward and backward search queues
105 forward_queue = deque([start])
106 backward_queue = deque([goal])

Callers 1

mainFunction · 0.85

Calls 3

expand_searchFunction · 0.85
construct_pathFunction · 0.85
reverseMethod · 0.80

Tested by

no test coverage detected