From 05f88ff86fb3c1cb3a3ff04eeeb85026eb862124 Mon Sep 17 00:00:00 2001 From: Saadanjum0 <160885369+Saadanjum0@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:01:33 +0500 Subject: [PATCH] fix(graph_search): avoid KeyError in BFS when a node has no outgoing edges find_shortest_path_bfs indexed self.graph[value] directly while expanding the queue. Any node reachable in the graph but not present as a key (a leaf node with no outgoing edges, as in a typical adjacency list) raised a KeyError instead of being treated as having no neighbors. The DFS methods already handle this correctly via self.graph.get(start, []); bring BFS in line with that and add a regression test. --- patterns/other/graph_search.py | 2 +- tests/test_graph_search.py | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 tests/test_graph_search.py diff --git a/patterns/other/graph_search.py b/patterns/other/graph_search.py index e3c92140..b4d19f00 100644 --- a/patterns/other/graph_search.py +++ b/patterns/other/graph_search.py @@ -78,7 +78,7 @@ def find_shortest_path_bfs(self, start: str, end: str) -> list[str] | None: while len(queue): value = queue.pop(0) - for node in self.graph[value]: + for node in self.graph.get(value, []): if node not in dist_to.keys(): edge_to[node] = value dist_to[node] = dist_to[value] + 1 diff --git a/tests/test_graph_search.py b/tests/test_graph_search.py new file mode 100644 index 00000000..dcbdce1a --- /dev/null +++ b/tests/test_graph_search.py @@ -0,0 +1,16 @@ +from patterns.other.graph_search import GraphSearch + + +def test_find_shortest_path_bfs_handles_leaf_nodes_without_outgoing_edges(): + # Leaf nodes ('C', 'D') have no entry in the graph dict, same as a + # real-world adjacency list that only lists nodes with outgoing edges. + graph = { + "A": ["B"], + "B": ["C", "D"], + } + search = GraphSearch(graph) + + assert search.find_shortest_path_bfs("A", "D") == ["A", "B", "D"] + # Searching for a node that is unreachable must still traverse through + # the leaf nodes without raising KeyError. + assert search.find_shortest_path_bfs("A", "Z") is None