Skip to content

fix(graph_search): avoid KeyError in BFS when a node has no outgoing edges - #506

Merged
faif merged 1 commit into
faif:masterfrom
Saadanjum0:fix/graph-search-bfs-keyerror
Oct 9, 2026
Merged

faif merged 1 commit into
faif:masterfrom
Saadanjum0:fix/graph-search-bfs-keyerror

Conversation

@Saadanjum0

Copy link
Copy Markdown
Contributor

find_shortest_path_bfs indexed self.graph[value] directly while expanding the BFS queue. Any node that is reachable in the graph but is not present as a dict key — a leaf node with no outgoing edges, which is normal for an adjacency-list graph — raised a KeyError instead of being treated as having no neighbors.

The other traversal methods on this class (find_path_dfs, find_all_paths_dfs, find_shortest_path_dfs) already handle this correctly via self.graph.get(start, []). This brings find_shortest_path_bfs in line with them.

Repro before the fix:

graph = {"A": ["B"], "B": ["C", "D"]}  # C and D are leaf nodes, no key in graph
GraphSearch(graph).find_shortest_path_bfs("A", "Z")  # KeyError: 'D'

Added a regression test (tests/test_graph_search.py) that fails before this change and passes after.

Ran the full suite locally with the new test passing. Also ran codespell, flake8, isort, black --check, and mypy on the changed files with no issues.

…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.
@faif
faif merged commit 089e574 into faif:master Oct 9, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants