Repository navigation
Fix BFS shortest distances for non-single-character node names - #15629
Shubham-Padkonde wants to merge 1 commit into
Conversation
rahul05ranjan
left a comment
There was a problem hiding this comment.
Nice catch — set(start) iterates the string, so it only worked while every node name was a single character. Confirmed the failure with a two-node graph: bfs_shortest_path_distance({"AB": ["B"], "B": []}, "AB", "B") returns -1 on the old code (the neighbour "B" is already in set("AB"), so it's never enqueued) and 1 with your change.
There's a second effect worth mentioning since it's the same root cause: start itself is not in visited ("G1" in set("G1") is False), so with the old code any edge pointing back to the start re-enqueues it and lets dist[start] be overwritten from 0. Your {start} fixes that too, because the if adjacent not in visited guard now covers the start node.
Nit: since the function is only correct when node names are hashable singletons (which {start} now guarantees), the docstring's -1 if no path exists contract is what the repro above exercises — might be worth adding one doctest with a multi-character node name, e.g. the {"AB": ["B"]} case, so this regression can't come back silently.
Describe your change
Initialize the visited set with the start node itself.
set(start)splits string node names into characters and raisesTypeErrorfor integer node names.For example,
bfs_shortest_path_distance({'AB': ['A'], 'A': ['C'], 'C': []}, 'AB', 'C')returns-1before this fix and2afterward. The edge from integer node0to1now returns1instead of raising.Validation on free-threaded Python 3.15: all 11 existing BFS doctest items pass. An external exhaustive check compares all source/target pairs in every directed four-node graph against Floyd-Warshall, with string, integer and tuple labels: 196,608 comparisons pass. Existing doctests remain unchanged, per the contribution guidance.
AI-assisted contribution.
Checklist